如何在 Angular 2 的 DatePipe 中设置语言环境? [英] How to set locale in DatePipe in Angular 2?
问题描述
我想使用欧洲格式显示日期 dd/MM/yyyy
但使用 DatePipe shortDate 格式它只使用美国日期样式显示 MM/dd/yyyy代码>.
我假设默认语言环境是 en_US.也许我在文档中遗漏了但如何更改 Angular2 应用程序中的默认语言环境设置?或者是否有某种方法可以将自定义格式传递给 DatePipe ?
I want to display Date using European format dd/MM/yyyy
but using DatePipe shortDate format it only display using US date style MM/dd/yyyy
.
I'm assuming thats the default locale is en_US. Maybe I am missing in the docs but how can I change the default locale settings in an Angular2 app? Or maybe is there some way to pass a custom format to DatePipe ?
推荐答案
从 Angular2 RC6 开始,您可以通过添加提供程序在应用模块中设置默认语言环境:
As of Angular2 RC6, you can set default locale in your app module, by adding a provider:
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
//otherProviders...
]
})
货币/日期/数字管道应该选择语言环境.LOCALE_ID 是一个 OpaqueToken,从 angular 导入/核心.
The Currency/Date/Number pipes should pick up the locale. LOCALE_ID is an OpaqueToken, to be imported from angular/core.
import { LOCALE_ID } from '@angular/core';
对于更高级的用例,您可能希望从服务中选择语言环境.创建使用日期管道的组件时,区域设置将被解析(一次):
For a more advanced use case, you may want to pick up locale from a service. Locale will be resolved (once) when component using date pipe is created:
{
provide: LOCALE_ID,
deps: [SettingsService], //some service handling global settings
useFactory: (settingsService) => settingsService.getLanguage() //returns locale string
}
希望它对你有用.
这篇关于如何在 Angular 2 的 DatePipe 中设置语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!