formatDate helper functionDatePipeLet’s explore this 2 use cases:
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 |
| 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.
DatePipe and formatDate parameters are pretty similar with each other:
| Parameter | Type | Meaning |
|---|---|---|
| value | `string | number |
| 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.
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.
formatDate function or date pipe ?formatDate mostly for times when you need to compose big strings from codedate pipe for times when you need to format a single date on HTML