The date pipe is the most convenient way to format dates with Angular. However, very often, we need to use a consistent date format throughout our application, which means that we have to pass that custom format every time we use the date pipe:
<span>Today is {{today | date: 'MM/dd/yy'}}</span>
Code language: HTML, XML (xml)
Of course, we could store that format in a constant and reuse that constant every time we use the pipe, but that’s not very convenient.
Luckily for us, since Angular 15, we can now set a default date format (and timezone) by configuring a new injection token called DATE_PIPE_DEFAULT_OPTIONS
.
It works by adding the following code to your dependency injection config (array of providers
) in app.modules.ts
:
providers: [
{
provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'MM/dd/yy'}
}
]
Code language: JavaScript (javascript)
With such a config in place, we can use our pipe without any parameters and have our default formatting applied automatically in our entire application:
<span>Today is {{today | date}}</span>
Code language: HTML, XML (xml)
The timezone can be customized as well with the timezone
property of that same DatePipeConfig
object.