首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Angular 2中如何在DatePipe中设置语言环境?

在Angular 2中如何在DatePipe中设置语言环境?
EN

Stack Overflow用户
提问于 2016-01-20 23:57:39
回答 14查看 204.3K关注 0票数 169

我想要显示日期使用欧洲格式dd/MM/yyyy,但使用DatePipe shortDate格式,它只显示使用美国日期样式MM/dd/yyyy

我假设默认的语言环境是en_US。也许我在文档中遗漏了,但我如何在Angular2应用程序中更改默认的区域设置?或者,是否有某种方法可以将自定义格式传递给DatePipe?

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2016-09-06 17:03:28

从Angular2 RC6开始,您可以通过添加提供程序在应用程序模块中设置默认区域设置:

代码语言:javascript
复制
@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
    //otherProviders...
  ]
})

Currency/Date/Number管道应该选择区域设置。LOCALE_ID是一个OpaqueToken,从angular/core导入。

代码语言:javascript
复制
import { LOCALE_ID } from '@angular/core';

对于更高级的用例,您可能希望从服务中获取区域设置。区域设置将在创建使用日期管道的组件时解析(一次):

代码语言:javascript
复制
{
  provide: LOCALE_ID,
  deps: [SettingsService],      //some service handling global settings
  useFactory: (settingsService) => settingsService.getLanguage()  //returns locale string
}

希望它能为你工作。

票数 298
EN

Stack Overflow用户

发布于 2017-08-11 06:34:57

如果你想为你的应用程序设置一次语言,LOCALE_ID的解决方案是很棒的。但是如果你想在运行时改变语言,它就不起作用了。对于这种情况,您可以实现自定义日期管道。

代码语言:javascript
复制
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)更改应用程序显示语言

代码语言:javascript
复制
this.translateService.use('en');

你的应用程序中的格式应该会自动更新。

使用示例:

代码语言:javascript
复制
<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>

或者查看我简单的“笔记”项目here

票数 85
EN

Stack Overflow用户

发布于 2018-01-24 03:51:43

对于angular5,上面的答案不再有效!

以下代码:

app.module.ts

代码语言:javascript
复制
@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
    //otherProviders...
  ]
})

导致以下错误:

错误:缺少区域设置"de-at“的区域设置数据。

使用angular5时,您必须自己加载和注册使用过的语言环境文件。

app.module.ts

代码语言:javascript
复制
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...
  ]
})

Documentation

票数 84
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34904683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档