我使用angular2默认DatePipe根据浏览器区域设置/语言格式化日期。
在我的情况下,它总是根据英语格式化日期。
app.module.ts
{
provide: LOCALE_ID, useValue: "hi"
}
在我的自定义管道中,我使用DI在构造函数中创建了DatePipe对象。
myDatePipe.ts
public constructor(private translate: TranslateService,private datePipe: DatePipe, , @Inject(LOCALE_ID) locale: string)) {
console.log(locale); // This log string 'hi'
}
public transform(value: string, format: string) {
// 'shortTime' format always return value in '5:15 am' format.
// 'longDate' format always return value in '28 दिसंबर 2017' format.
return this.datePipe.transform(value, format);
}
我通过记录Locale_ID记录了当前应用的语言,并将其记录为“hi”。
答案 0 :(得分:0)
您最好的选择是创建自己的shortDate管道并使用NGX转换服务,引入浏览器语言并使用它来转换日期。这是我正在使用的短期管道的示例
这是Angular 6,所以我也在使用@ angular / common中可用的新formatDate功能
import { Pipe, PipeTransform} from '@angular/core';
import { formatDate } from '@angular/common';
import { TranslateService } from '@ngx-translate/core';
@Pipe({
name: 'shortDate'
})
export class ShortDatePipe implements PipeTransform {
constructor(private translateService: TranslateService) { }
transform(value: string): string {
var language: string = this.translateService.getBrowserCultureLang();
console.log(language);
return (value == "" || value == null) ? "" : formatDate(value, 'shortDate', language);
}
}
如果您不在angular6上,则需要导入datePipe,在构造函数中放置一个datepipe并使用它的transform
这样的事情(未经证实或测试,就在我的头上)
import { DatePipe } from '@angular/common';
...
constructor(private translateService: TranslateService,
private datePipe: DatePipe ) { }
...
return this.datePipe.transform( value, 'shortDate',language);