Home > Back-end >  LOCALE_ID en-GB results in incorrect date formats
LOCALE_ID en-GB results in incorrect date formats

Time:11-17

I'm having troubles setting up the correct locales in my angular app. According to the docs I've added the following snippet to my angular.json file.

"projects": {
  "appname": {
    ...,
    "i18n": {
      "sourceLocale": "nl-NL"
    },

In my app.module.ts I've addod the following.

providers: [
  {
    provide: LOCALE_ID,
    useValue: "en-GB"
  }
]

However, when I use the datePipe to format a date like this...

<p>{{ '2021-11-16' | date : 'longDate' }}</p>

The result is November 16, 2021, but I'm expecting 16 November 2021

It is as if the locale part of en-GB is ignored completely. It does work when I set the sourceLocale in angular.json to en-GB, but most of the time my app will be Dutch.

I feel I'm missing something. The angular docs aren't that helpful. I've found docs using the ISO 639-2 code as the LOCALE_ID, which omits the locale part completely. See https://angular.io/guide/i18n-optional-manual-runtime-locale There are also other docs that do use the unicode locale id, see https://angular.io/api/core/LOCALE_ID

All in all. It's not working as expected.

CodePudding user response:

Looking at the Angular DatePipe documentation might help you. the longDate translates to MMMM d, y. In your case you would need something like this:

<p>{{ '2021-11-16' | date : 'dd MMMM y' }}</p>

You might need to tweak this a little since I do not have enough info with only one example.

CodePudding user response:

I don't use i18n for this, I'm going to tell you how I usually do it. P.D: I left you a working code HERE

To be able to use another language, we must first register it with the registerLocaleData function in app.module.ts:

import myLocaleNl from '@angular/common/locales/nl';
import {registerLocaleData} from '@angular/common/'; //function to register it.
 
registerLocaleData(myLocaleNl );

Once we have registered a locale, we could already use it in the pipe as 4 parameter. e.g:

{{ date | date: "longDate":"": "nl" }}

We can register as many locale as we need:

import myLocaleEs from '@angular/common/locals/en'.
import myLocaleFr from '@angular/common/locals/fr'
import {registerLocaleData} from '@angular/common/';
registerLocaleData(myLocaleEs);
registerLocaleData(myLocaleFr);

Register a locale in a GLOBAL way To register it globally (so that it is not necessary to specify it every time in the pipes and it is applied by default), we "register" it in the app.module.ts PROVIDER section:

import { LOCALE_ID} from '@angular/core';

  providers: [
    {provide: LOCALE_ID, useValue: 'nl'} // Same value used up
  ],
  • Related