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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34904683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:01:43  来源:igfitidea点击:

How to set locale in DatePipe in Angular 2?

javascriptangulardate-pipe

提问by nsbm

I want to display Date using European format dd/MM/yyyybut using DatePipe shortDateformat 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 ?

我想使用欧洲格式显示日期dd/MM/yyyy但使用 DatePipe shortDate格式它只使用美国日期样式显示MM/dd/yyyy
我假设默认语言环境是 en_US。也许我在文档中遗漏了,但如何更改 Angular2 应用程序中的默认语言环境设置?或者也许有什么方法可以将自定义格式传递给 DatePipe ?

回答by corolla

As of Angular2 RC6, you can set default locale in your app module, by adding a provider:

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

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
    //otherProviders...
  ]
})

The Currency/Date/Number pipes should pick up the locale. LOCALE_ID is an OpaqueToken, to be imported from angular/core.

Currency/Date/Number 管道应该选择区域设置。LOCALE_ID 是一个OpaqueToken,从 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
}

Hope it works for you.

希望对你有效。

回答by Milan Hlinák

Solution with LOCALE_ID is great if you want to set the language for your app once. But it doesn't work, if you want to change the language during runtime. For this case you can implement custom date pipe.

如果您想为您的应用设置一次语言,使用 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);
  }

}

Now if you change the app display language using TranslateService (see ngx-translate)

现在,如果您使用 TranslateService 更改应用程序显示语言(请参阅ngx-translate

this.translateService.use('en');

the formats within your app should automatically being updated.

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

Example of use:

使用示例:

<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>

or check my simple "Notes" project here.

或者在这里查看我简单的“Notes”项目。

enter image description here

在此处输入图片说明

回答by zgue

With angular5the above answer no longer works!

有了angular5上面的回答不再起作用!

The following code:

以下代码:

app.module.ts

app.module.ts

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
    //otherProviders...
  ]
})

Leads to following error:

导致以下错误:

Error: Missing locale data for the locale "de-at".

错误:缺少语言环境“de-at”的语言环境数据。

With angular5you have to load and register the used locale file on your own.

随着angular5你必须加载并注册在自己所使用的语言环境文件。

app.module.ts

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...
  ]
})

Documentation

文档

回答by knnhcn

If you use TranslateServicefrom @ngx-translate/core, below is a version without creating a new pipe which works with switching dynamically on runtime (tested on Angular 7). Using DatePipe's localeparameter (docs):

如果你使用TranslateServicefrom @ngx-translate/core,下面是一个没有创建新管道的版本,它可以在运行时动态切换(在 Angular 7 上测试)。使用 DatePipe 的locale参数 ( docs):

First, declare the locales you use in your app, e.g. in app.component.ts:

首先,声明您在应用程序中使用的语言环境,例如app.component.ts

import localeIt from '@angular/common/locales/it';
import localeEnGb from '@angular/common/locales/en-GB';
.
.
.
ngOnInit() {
    registerLocaleData(localeIt, 'it-IT');
    registerLocaleData(localeEnGb, 'en-GB');
}

Then, use your pipe dynamically:

然后,动态使用您的管道:

myComponent.component.html

myComponent.component.html

<span>{{ dueDate | date: 'shortDate' : '' : translateService.currentLang }}</span>

myComponent.component.ts

myComponent.component.ts

 constructor(public translateService: TranslateService) { ... }

回答by Mark Farmiloe

I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:

我查看了 date_pipe.ts,它有两个有趣的信息。靠近顶部的是以下两行:

// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';

Near the bottom is this line:

靠近底部的是这条线:

return DateFormatter.format(value, defaultLocale, pattern);

This suggests to me that the date pipe is currently hard-coded to be 'en-US'.

这向我表明日期管道目前被硬编码为“en-US”。

Please enlighten me if I am wrong.

如果我错了,请赐教。

回答by Alejandro del Río

On app.module.ts add the following imports. There is a list of LOCALE options here.

在 app.module.ts 上添加以下导入。有区域设置选项列表在这里

import es from '@angular/common/locales/es';
import { registerLocaleData } from '@angular/common';
registerLocaleData(es);

Then add the provider

然后添加提供者

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "es-ES" }, //your locale
  ]
})

Use pipes in html. Here is the angular documentationfor this.

在 html 中使用管道。这是用于此的角度文档

{{ dateObject | date: 'medium' }}

回答by Langley

You do something like this:

你做这样的事情:

{{ dateObj | date:'shortDate' }}

{{ dateObj | date:'shortDate' }}

or

或者

{{ dateObj | date:'ddmmy' }}

{{ dateObj | date:'ddmmy' }}

See: https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html

请参阅:https: //angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html

回答by hydrangenius

I was struggling with the same issue and didn't work for me using this

我在同样的问题上苦苦挣扎,使用它对我不起作用

{{dateObj | date:'ydM'}}

So, I've tried a workaround, not the best solution but it worked:

所以,我尝试了一种解决方法,不是最好的解决方案,但它奏效了:

{{dateObj | date:'d'}}/{{dateObj | date:'M'}}/{{dateObj | date:'y'}}

I can always create a custom pipe.

我总是可以创建自定义管道。

回答by vidalsasoon

For those having problems with AOT, you need to do it a little differently with a useFactory:

对于那些在使用 AOT 时遇到问题的人,您需要使用 useFactory 做一些不同的事情:

export function getCulture() {
    return 'fr-CA';
}

@NgModule({
  providers: [
    { provide: LOCALE_ID, useFactory: getCulture },
    //otherProviders...
  ]
})

回答by LizanLycan

Ok, I propose this solution, very simple, using ngx-translate

好的,我提出这个解决方案,非常简单,使用 ngx-translate

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): any {
    const date = new Date(value);

    const options = { weekday: 'long',
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit'
                    };

    return date.toLocaleString(this.translateService.currentLang, options);
  }

}