Categories
Angular Answers

How to set locale in DatePipe in Angular?

Spread the love

Sometimes, we want to set locale in DatePipe in Angular.

In this article, we’ll look at how to set locale in DatePipe in Angular.

How to set locale in DatePipe in Angular?

To set locale in DatePipe in Angular, we can call DatePipe with the current locale.

For instance, we write

import { DatePipe } from "@angular/common";
import { Pipe, PipeTransform } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";

@Pipe({
  name: "localizedDate",
  pure: false,
})
export class LocalizedDatePipe implements PipeTransform {
  constructor(private translateService: TranslateService) {}

  transform(value: any, pattern: string = "mediumDate"): any {
    const datePipe: DatePipe = new DatePipe(this.translateService.currentLang);
    return datePipe.transform(value, pattern);
  }
}

to create the LocalizedDatePipe pipe class that has the transform method.

In it, we create a DatePipe instance with the current language we get from this.translateService.currentLang.

Then we call datePipe.transform with the value and pattern.

Conclusion

To set locale in DatePipe in Angular, we can call DatePipe with the current locale.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *