2

I am displaying date in html like this

<span >{{ item.lastModified | date : 'MMM d, y' }}</span>

So the date displays something like this Jul 20, 2021 Now when I change my browser language I need the month to change to that language the language should be picked up dynamically , but its displaying in English. How do I do this?

dev_101
  • 321
  • 4
  • 14

1 Answers1

4

You need to set yours 'locale':

  1. In your app.module.ts:
    // Import all the languages you need (you can add any language you want i.e: '../locales/en-GB', '/locales/en-US', ... ).
    // In this example, I will use 'es' for Spanish and 'fr' for French:
    import myLocaleEs from '@angular/common/locales/es'
    import myLocaleFr from '@angular/common/locales/fr'

    import {registerLocaleData} from '@angular/common';

    registerLocaleData(myLocaleEs);
    registerLocaleData(myLocaleFr);
  1. In your HTML:

    // "en" is always by default, you don't need to register
    {{ fecha | date: "long":"":"en" }}
    
    {{ fecha | date: "long":"":"es" }}

    
    {{ fecha | date: "short":"":"fr" }}
or  {{ fecha | date: 'MMM d, y':"":"fr" }}

Set Globally

It is a way to set "globaly" your favorite locale (if it's different to "en", the default), so then you don't need to write it down in every pipe:

You need to add to app.module.ts, besides all the above code, this import and the PROVIDERS section:

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

...
providers: [
    {provide: LOCALE_ID, useValue: 'es'} // Same value you used above ‘es’ or 'fr' or whatever you had registered
  ],
...

displayName
  • 986
  • 16
  • 40