Search code examples
angularinternationalizationlocaledate-pipe

Why angular date pipe do not support locale language default format like Intl.DateTimeFormat?


I am using angular date pipe for date formatting. I want to format date based on user/client locale. For example 'mm/dd/yyyy' for English US(en-US) and dd.mm.yyyy for German(de-de). Angular have format options like short, medium and long. They do not match the locale default format. If i go for customized date format, I do not have the locale separator. Intl DateTimeFormat provides the exact formatted date. Is there any way to achieve this with angular date pipe?


Solution

  • **EDIT**

    I can't see that the recent Angular docs mention registerLocaleData, so I assume it can be ignored now, so you can skip the first part. I guess Angular figures out which locales you use automatically, or all locale data is bundled into Angular.


    The first thing to make sure is that you have loaded the locale data. You can do this in `app.module.ts` as stated in the documentation:
    import { registerLocaleData } from '@angular/common';
    import localeDe from '@angular/common/locales/de';
    
    registerLocaleData(localeDe);
    

    Then, you have two alternatives.

    1. You can set the LOCALE_ID variable to your preferred locale (de-DE in your case). This can be done either by using the --i18nLocale flag in ng build or ng serve, or it can be done by providing a value during bootstrap (see documentation). If you use this, the date will be formatted according to that locale's rules anywhere you use it.
    2. You can set the locale as the third parameter in DatePipe. If you use this approach, it will only affect that specific usage of the date pipe. The parameters are separated by :, and if you want the default behavior for some prior parameter you can set it to undefined. The following example shows the date and time using the de-DE date format without using any timezone offset: myDate | date : 'medium' : undefined : 'de-DE'. Check out this stackblitz for more examples