Reputation: 2111
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?
Upvotes: 0
Views: 3250
Reputation: 7457
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.
Upvotes: 1