Angular Date Pipe & formatting dates in Angular (with code)

In Angular, the DatePipe is a pipe that formats a date value according to a set of predefined formats or a custom format. It’s a convenient way to display dates in a template and can help to ensure that dates are displayed in a consistent format across your application.

To use the DatePipe, you first need to import it from the @angular/common module in your component or service:

import { DatePipe } from '@angular/common';

Once you’ve imported the DatePipe, you can use it in your template by applying it to a date expression using the pipe (|) symbol. For example:

{{ date | date }}

By default, the DatePipe will format the date using the medium date format, which is equivalent to ‘MMM d, y’ in the en-US locale (e.g. “Jan 1, 2021”).

You can also specify a custom format for the date by passing it as an argument to the DatePipe. For example:

{{ date | date:'shortDate' }}

This will format the date using the short date format, which is equivalent to ‘M/d/yy’ in the en-US locale (e.g. “1/1/21”).

There are several predefined formats available in Angular, including:

  • ‘shortDate’: equivalent to ‘M/d/yy’ (e.g. “1/1/21”)
  • ‘mediumDate’: equivalent to ‘MMM d, y’ (e.g. “Jan 1, 2021”)
  • ‘longDate’: equivalent to ‘MMMM d, y’ (e.g. “January 1, 2021”)
  • ‘fullDate’: equivalent to ‘EEEE, MMMM d, y’ (e.g. “Friday, January 1, 2021”)

You can also specify a custom format string using a pattern that follows the Unicode Technical Standard #35. For example:

{{ date | date:'yyyy/MM/dd HH:mm' }}

This will format the date as “2021/01/01 12:00”.

In addition to formatting dates, the DatePipe can also be used to parse dates from strings. To parse a date from a string, you can pass the string as an argument to the DatePipe and use the ‘parse’ format. For example:

{{ '2021-01-01' | date:'parse' }}

This will parse the string “2021-01-01” into a Date object.

By using the DatePipe, you can easily format and parse dates in your Angular application. It’s a convenient and reliable way to work with dates in templates and can help to ensure that dates are displayed consistently across your application.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts