Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading