Depends on your use case:
- from typescript code using
formatDate
helper function - from HTML templates using
DatePipe
Let's explore this 2 use cases:
Internationalize dates from code:
Angular helps us by providing formatDate
helper function from @angular/common
package.
How to use formatDate
?
formatDate
receives 4 parameters:
Parameter | Type | Meaning |
---|---|---|
value | string, number, Date | date as string, number or a javascript Date object |
format | string | should look like DateTime pipe formats |
locale | string | use @Inject(LOCALE_ID) to get current user locale |
timezone | string | timezone abbreviation, defaults to local system timezone |
Example:
import { Component } from "@angular/core"; import { LOCALE_ID, Inject } from "@angular/core"; import { formatDate } from "@angular/common"; import { of } from "rxjs"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { currentDate = new Date(); dateFormat = "dd MMM yyyy"; currentDate$ = of(formatDate(this.currentDate, this.dateFormat, this.locale)); constructor(@Inject(LOCALE_ID) public locale: string) {} }
The above Angular code should show current date as 14 Mar 2020
.
Internationalize dates from HTML:
DatePipe and formatDate
parameters are pretty similar with each other:
Parameter | Type | Meaning |
---|---|---|
value | string, number, Date | date as string, number or a javascript Date object |
format | string | should look like DateTime pipe formats |
timezone | string | timezone abbreviation, defaults to local system timezone |
locale | string | use @Inject(LOCALE_ID) to get current user locale |
In HTML we could use date
pipe:
{{ (currentDate) | date:dateFormat:'GMT':locale }}
The above Angular code should show current date as 14 Mar 2020
.
Difference in parameters positioning:
formatDate
timezone it's at the end and date
pipe timezone it's the third one.
So, there is a switch between the last two parameters in terms of positioning.
When to use formatDate
function or date
pipe ?
-
formatDate
mostly for times when you need to compose big strings from code -
date
pipe for times when you need to format a single date on HTML
Top comments (0)