0

In Angular2, we can format the date using DatePipe using typescript as:

new DatePipe(navigator.language || 'en-US').transform(mydate, 'medium')

But, I want to do this on HTML side. I read that I can do like this:

mydate | date:'medium'

But, this is still not taking care of localization, as in, its not passing the language. How do I modify the usage of pipe in my HTML so I can pass the language also?

user1892775
  • 2,001
  • 6
  • 37
  • 58
  • Have you seen this: https://stackoverflow.com/questions/34904683/how-to-set-locale-in-datepipe-in-angular-2 – DeborahK Sep 07 '17 at 23:19

1 Answers1

1

If you want to use the DatePipe you are limited to the defaults provided there, but if you want to set the locale in you template, whether it's a literal or comes from a variable, you can define a custom pipe like this:

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({name: 'dateWithLocale'})
export class DateWithLocalePipe implements PipeTransform {
  constructor(){}
  transform(value: string, locale: string, pattern: string): number {
    return new DatePipe(locale).transform(value, pattern);
  }
}

and use it like this:

{{time | dateWithLocale: 'en-US' : 'short'}}

You can see the working example here.

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66