Austin Reid
Austin Reid

Reputation: 381

How to set dates to locale in Angular?

So i have an angular application (angular 8) that will be used by the UK, Mauritius and South Africa (potentially more as well).

How can I set the dates be based on the locale of the users?

Will I use a custom pipe? Or set it as some sort of provider in the app.module?

Thanks.

Upvotes: 1

Views: 5576

Answers (2)

Sen Alexandru
Sen Alexandru

Reputation: 2293

In app.module I set the MAT_DATE_LOCALE value like this:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true,
    },
    { provide: MAT_DATE_LOCALE, useValue: 'ro-RO' },  //YOUR DESIRED LOCALE
    DatePipe
  ],

Also, in other controls like mat-table I use pipes:

<td mat-cell *matCellDef="let element" class="alignLeft"> {{ element.Date | date: 'dd/MM/yyyy HH:mm' }}

When the content is dynamic you can try to use this:

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

...

constructor(
  @Inject(LOCALE_ID) public locale: string
) { }

and send it as parameter to a custom pipe or other relevant method.

Let me know if that worked for you

Upvotes: 1

Mujadid Mughal
Mujadid Mughal

Reputation: 2663

Normally I make use of moment library, and would create a pipe to format the date in the desired language, e.g.

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
    name: 'customdate'
})
export class CustomDatePipe implements PipeTransform {

    constructor() { }

    transform(value: any, lng:string) {
            return moment(value).lang(lng).format("MMM");
        
    }
}

So e.g.

{{item.date | customdate : 'en-us'}} = March

{{item.date | customdate : 'de'}} = März

{{item.date | customdate : 'es'}} = Marzo

Upvotes: 1

Related Questions