We mentioned the default config options for the date
pipe in Angular yesterday.
Did you know we can also format dates in our Typescript code using a formatDate
function?
This function has the same signature as the date pipe, which makes perfect sense because… That’s the function used by the pipe itself (source code here):
formatDate(value: string | number | Date,
format: string,
locale: string,
timezone?: string): string
Code language: JavaScript (javascript)
All you need to use that function is to import it from @angular/common
:
import {formatDate} from "@angular/common";
Code language: JavaScript (javascript)
The only downside of that function is that there is no default format or locale, so we have to pass those two values as parameters, which isn’t the case for the date
pipe.
And by the way, similar functions are available for numbers, currencies, and percentages:
For more information on those functions, I have this tutorial on formatting dates and numbers with Angular.