How to format the date in AngularJS

In AngularJS, you can use the following to format the date as a string:

Usage

HTML

{{ date_expression | date : format : timezone}}

JS

filter('date')(date, format, timezone)

Where:

  • date: is the date that needs to be formatted
  • format: are the formatting rules (optional)
  • timezone: is the applied timezone

Date formats

  • yyyy: This is the four digit representation of year.
    e.g., 20 => 0020
  • yy: two digit representation of year, padded (00-99).
    e.g., 2020 => 20
  • y: one digit representation of year.
    e.g., 0001 => 1
  • MMMM: month in year (January-December)
  • MMM: month in year (Jan-Dec)
  • MM: month in year (01-12)
  • M: month in year (1-12)
  • LLLL: stand-alone month in year (January-December)
  • dd: day in month (01-31)
  • d: day in month (1-31)
  • EEEE: day in Week(Sunday-Saturday)
  • EEE: day in Week (Sun-Sat)
  • HH: hour in day (00-23)
  • H: hour in day (0-23)
  • hh: hour in AM/PM (01-12)
  • h: hour in AM/PM (1-12)
  • mm: minute in hour (00-59)
  • m: minute in hour (0-59)
  • ss: second in minute (00-59)
  • s: second in minute (0-59)
  • sss: millisecond in second (000-999)
  • a: AM/PM marker
  • Z: four digit (+sign) representation of the timezone offset (-1200-+1200)
  • ww: week of year, padded (00-53)
  • w: week of year (0-53).
  • G, GG, GGG: abbreviation of era (AD)
  • GGGG: long form of era (Anno Domini)

Pre-defined Formats

These dates can also be formatted in one of the following formats:

  • medium: in the format MMM d, y h:mm:ss a
    e.g., Dec 4, 2020 10:02:18 AM)
  • short: in the format M/d/yy h:mm a
    e.g., 12/4/20 10:02 AM
  • fullDate: in the format EEEE, MMMM d, y for en_US locale
    e.g., Saturday, December 4, 2020
  • longDate: in the format MMMM d, y
    e.g., December 4, 2020
  • mediumDate: in the format MMM d, y
    e.g., Dec 4, 2020
  • shortDate: in the format M/d/yy
    e.g., 12/4/20
  • mediumTime: in the format h:mm:ss a
    e.g., 10:02:18 AM
  • shortTime: in the format h:mm a
    e.g., 10:02 AM AM

Custom text

We can also format them using literal values; however, they need to be enclosed within single quotes e.g., “h ‘o clock’”.

For more details, refer to the official documentation.

Copyright ©2024 Educative, Inc. All rights reserved