我想要显示日期使用欧洲格式dd/MM/yyyy
,但使用DatePipe shortDate格式,它只显示使用美国日期样式MM/dd/yyyy
。
我假设默认的语言环境是en_US。也许我在文档中遗漏了,但我如何在Angular2应用程序中更改默认的区域设置?或者,是否有某种方法可以将自定义格式传递给DatePipe?
发布于 2016-09-06 17:03:28
从Angular2 RC6开始,您可以通过添加提供程序在应用程序模块中设置默认区域设置:
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
//otherProviders...
]
})
Currency/Date/Number管道应该选择区域设置。LOCALE_ID是一个OpaqueToken,从angular/core导入。
import { LOCALE_ID } from '@angular/core';
对于更高级的用例,您可能希望从服务中获取区域设置。区域设置将在创建使用日期管道的组件时解析(一次):
{
provide: LOCALE_ID,
deps: [SettingsService], //some service handling global settings
useFactory: (settingsService) => settingsService.getLanguage() //returns locale string
}
希望它能为你工作。
发布于 2017-08-11 06:34:57
如果你想为你的应用程序设置一次语言,LOCALE_ID的解决方案是很棒的。但是如果你想在运行时改变语言,它就不起作用了。对于这种情况,您可以实现自定义日期管道。
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);
}
}
现在,如果您使用TranslateService (请参阅ngx-translate)更改应用程序显示语言
this.translateService.use('en');
你的应用程序中的格式应该会自动更新。
使用示例:
<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>
或者查看我简单的“笔记”项目here。
发布于 2018-01-24 03:51:43
对于angular5
,上面的答案不再有效!
以下代码:
app.module.ts
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
//otherProviders...
]
})
导致以下错误:
错误:缺少区域设置"de-at“的区域设置数据。
使用angular5
时,您必须自己加载和注册使用过的语言环境文件。
app.module.ts
import { NgModule, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeDeAt from '@angular/common/locales/de-at';
registerLocaleData(localeDeAt);
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
//otherProviders...
]
})
https://stackoverflow.com/questions/34904683
复制相似问题