Formatting functions in Angular

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): stringCode 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.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.