0

In my Angular 8 app, I can't manage to display date fields in a localized form. I'd like to come up with something like the following:

  • in English : "February 18, 2020 12:15:50"
  • in French : "18 février 2020, 12:15:50"

I guess I should use Angular's DatePipe:

{{ myDate | date }}

For all other localization purposes, I am using ngx-translate (not Angular i18n). It gives me access to the current language (the user can switch language on the fly), but I don't know how I can link TranslateService#currentLang with the language used in the DatePipe. Is there a way to do so in a simple way?

Ivan dal Bosco
  • 3,233
  • 4
  • 19
  • 24

2 Answers2

1

angular provides a lot of locales, so use can register right locale which will be used in date pipe.

// app.module.ts

import { registerLocaleData } from '@angular/common';
import frenchLocale from '@angular/common/locales/fr';
import { LOCALE_ID, NgModule } from '@angular/core';

registerLocaleData(frenchLocale);

Then you can specify locale in date pipe

someDate | date: null: null: 'fr'

or overried default locale

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "fr" }
  ]
})

UPDATE

Angular i18n uses differential builds, but ngx-translate fetches needed locale on demand. As we can not combine those approaches, we can create custom date pipe, which would meet our requirements.

I created demo with current TranslateService locale provider and custom date pipe which reactive equivalent of original date.pipe

shumih
  • 437
  • 3
  • 7
  • Thanks for your helpful answer. However, how can I avoid to hard-code ```'en'``` in ```someDate | date: null: null: 'en'``` and instead put "the current language"? – Ivan dal Bosco May 15 '20 at 12:45
0

Yes, you can use DatePipe. As you can see, it use LOCALE_ID token be default. If you use Angular CLI, LOCALE_ID is provided automatically:

A locale code for the locale format rules to use. When not supplied, uses the value of LOCALE_ID, which is en-US by default

HTN
  • 3,388
  • 1
  • 8
  • 18