Angular DatePipe: change the default Date format in all your templates

Updated: 2022-10-27

In Angular, we can quickly format the dates in our HTML page using the | Date pipe.

As example in Switzerland we use the format date | Date: ‘dd.MM.yyyy, this feature of Angular works very well.

If we use the Pipe without specifying the format to show it will show the date with the shortDate format that is equivalent to 'M/d/yy'.

How to set the default format in all the pages using the configuration

Starting from Angular 15 the solution to this common issue comes out of the box.

A new feature offers the possibility to set a default format for the DatePipe.

With Angular 15 you can declare an InjectionToken that defines the date format to use as default in your application.

Here you can have a preview of the Documentation: Angular 15 Preview: DATA_PIPE_DEFAULT_OPTIONS

The DATA_PIPE_DEFAULT_OPTIONS replaces and enrich DATE_PIPE_DEFAULT_TIMEZONE deprecated in Angular 15.

export declare const DATE_PIPE_DEFAULT_OPTIONS: InjectionToken<DatePipeConfig>; 

DatePipeConfig allows the customization of the dateFormat and the timezone. The deprecated DATE_PIPE_DEFAULT_TIMEZONE was specific to the ... timezone configuration.

export declare interface DatePipeConfig { 
    dateFormat: string; 
    timezone: string; 
} 

In my case, if I want to apply the Swiss format of the date to all the DatePipe in the application I can define a new provider in the Angular AppModule:

... 
import {DATE_PIPE_DEFAULT_OPTIONS} from "@angular/common"; 
... 
@NgModule({ 
}) 
 
declarations: [   
  AppComponent 
], 
imports: [   
  BrowserModule 
], 
providers: [{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'dd.MM.yyy'}}], 
bootstrap: [AppComponent] 

This line of configuration: providers: [{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'dd.MM.yyy'}}],

Transform all the dates in my html templates (e.g. Date: {{getDate() | date}}) from Date: Oct 27,2022 to Date: 27.10.2022.

... but I am using an older version of Angular

If you are still using a version < 15. Your best option is to extend the current DatePipe changing the default format or define the format for every DatePipe in your templates.

References

DatePipe source code on GitHub

DatePipe documentation

The Pull Request for the changes in Angular 15

Default Time Zone InjectionToken, deprecated in version 15


You could be interested in

Right click context menu with Angular

Right click custom menu inside dynamic lists with Angular Material
2020-05-31

Enums in Angular templates

How to use enum in the html template
2019-01-21
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).