To translate dates in Angular, we can think about three approaches: setting the app global locale, passing a specific locale to Angular date through a

How to Create a Localized Date Pipe in Angular ๐Ÿ“…

submited by
Style Pass
2022-01-20 13:00:07

To translate dates in Angular, we can think about three approaches: setting the app global locale, passing a specific locale to Angular date through arguments, or creating a custom localizedDate pipe. The localizedDate pipe combines Angular date pipe and the lib ngx-translate. This solution prevents us from explicitly passing the locale as an argument in the template while still being able to dynamically change the dates' locale without reloading the app. Those aspects make the localizedDate pipe impure like [ngx-translate]'s translate pipe.

We use pipes either in a service or a template (the HTML code). In the following example, we are using the template syntax of the slice pipe and the uppercase pipe.

Angular provides a built-in date pipe. It transforms a date into a string value (eg. 2021-03-21 -> Mar 21, 2021). The date pipe uses the app locale as its default locale (eg. 2021-03-21 -> 21 mars 2021 for a french locale).

The date pipe uses the LOCALE_ID to determine the default locale to use. By default, LOCALE_ID is set to en-US. We can change the app locale by LOCALE_ID setting in the AppModule.

Leave a Comment