htmlangulartypescriptangular-pipedate-pipe

Angular DatePipe with locale usage


I want to display the date in HTML depending on the set/used locale. For display purposes I want to display it in English or German - depending on the users decision. This means the user select the locale 'de' or 'en'.

The default way to display the date is

 <span>{{ data.selDate | date: "mediumDate" }}</span>

According to the documentation I have {{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}. But this code won't work

 <span>{{ data.selDate | date: "mediumDate" :'':"de-DE" }}</span>
 <span>{{ data.selDate | date: "mediumDate" :undefined:"de-DE" }}</span>

How to specify it in the DatePipe?


Solution

  • You need to import the additional locale's

    You can try:

    component.html

    <button (click)="switch('en-US')">Eng</button>
    <button (click)="switch('de-DE')">Deu</button>
    
    <span>{{ data.selDate | date: 'mediumDate':'': current }}</span>
    

    app.module.ts

    import { registerLocaleData } from '@angular/common';
    import localeEn from '@angular/common/locales/en';
    import localeDe from '@angular/common/locales/de';
    
    registerLocaleData(localeDe);
    registerLocaleData(localeEn);
    

    component.ts

    current: string = 'de-De';
    
    switch(new: string): void {
      this.current = new;
    }
    

    NOTE: make sure selDate is a valid date

    StackBlitz