如何在Angular 2中的DatePipe中设置区域设置?

nsb*_*sbm 121 javascript date-pipe angular

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

cor*_*lla 251

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

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

货币/日期/数字管道应该选择区域设置.LOCALE_ID是一个OpaqueToken,从angular/core导入.

import { LOCALE_ID } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

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

{
  provide: LOCALE_ID,
  deps: [SettingsService],      //some service handling global settings
  useFactory: (settingsService) => settingsService.getLanguage()  //returns locale string
}
Run Code Online (Sandbox Code Playgroud)

希望对你有效.

  • 令我惊讶的是,这似乎仍未在任何地方记录.不在日期管道页面(https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html)上,而不是在常规管道页面上(https://angular.io/docs) /ts/latest/guide/pipes.html)这个问题实际上是Google上的第一个问题(https://www.google.com/search?q=angular%202%20locales&rct=j).很棒的发现. (33认同)
  • 要在代码中使用管道,您现在必须将其格式化为`new CurrencyPipe('en-US');`.希望这对某些内容很有用,因为这是Google搜索我的问题时的第一个结果. (2认同)
  • 我在这个主题上也挣扎了很多,我希望我写的关于这个的文章可以帮助一些人:https://medium.com/dailyjs/dynamic-locales-in-angular-dd9a527ebe1f (2认同)

Mil*_*nák 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);
  }

}
Run Code Online (Sandbox Code Playgroud)

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

this.translateService.use('en');
Run Code Online (Sandbox Code Playgroud)

应用中的格式应自动更新.

使用示例:

<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>
Run Code Online (Sandbox Code Playgroud)

或者在这里查看我的简单"笔记"项目.

在此输入图像描述

  • 它的工作原理,但注意使用"不纯"管道比"纯"管慢.正如[Angular guide](https://angular.io/guide/pipes)所说:Angular在每个组件更改检测周期内执行不纯的管道.经常调用不纯的管道,就像每次按键或鼠标移动一样.考虑到这种担忧,要非常谨慎地实施不纯净的管道.昂贵,长时间运行的管道可能会破坏用户体验. (2认同)

zgu*_*gue 52

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

以下代码:

app.module.ts

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

导致以下错误:

错误:缺少区域设置"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...
  ]
})
Run Code Online (Sandbox Code Playgroud)

文档

  • 好吧,这阻止了我再次头痛..谢谢!该文档有点复杂,因为我认为“registerLocaleData”就足够了,但事实并非如此。 (3认同)

小智 12

我看过date_pipe.ts,它有两位感兴趣的信息.靠近顶部的是以下两行:

// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';
Run Code Online (Sandbox Code Playgroud)

这条线靠近底部:

return DateFormatter.format(value, defaultLocale, pattern);
Run Code Online (Sandbox Code Playgroud)

这告诉我,日期管道目前硬编码为'en-US'.

如果我错了,请赐教.


knn*_*hcn 11

如果您使用TranslateServicefrom @ngx-translate/core,则下面是未创建新管道的版本,该管道可在运行时动态切换(在Angular 7上进行了测试)。使用DatePipe的locale参数(docs):

首先,声明您在应用中使用的语言环境,例如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');
}
Run Code Online (Sandbox Code Playgroud)

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

myComponent.component.html

<span>{{ dueDate | date: 'shortDate' : '' : translateService.currentLang }}</span>
Run Code Online (Sandbox Code Playgroud)

myComponent.component.ts

 constructor(public translateService: TranslateService) { ... }
Run Code Online (Sandbox Code Playgroud)

  • 这真是令人惊讶的好。你甚至不需要 @ngx-translate 。您能解释一下模板中的语句的作用吗? (3认同)
  • @lama,**dueDate** *(您想要格式化的任何日期)* **| date: 'shortDate'** *(对应于 'format' 的日期管道的第一个参数)* : '' *(第二个参数 =&gt; timeZone, "如果未提供,则使用最终用户的本地系统时区"。)* : **trasnlateService.currentLang** *(第三个参数 =&gt; 本地),勾选这个 [DatePipe](https://angular.io/api/common/DatePipe#parameters)* (3认同)
  • 我认为最好的解决方案,但在我的情况下,如果没有 @ngx-translate 和 TranslateService ,效果也很好。 (2认同)

Ale*_*Río 6

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

import es from '@angular/common/locales/es';
import { registerLocaleData } from '@angular/common';
registerLocaleData(es);
Run Code Online (Sandbox Code Playgroud)

然后添加提供者

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

使用html中的管道。这是有关角度的文档

{{ dateObject | date: 'medium' }}
Run Code Online (Sandbox Code Playgroud)


Lan*_*ley 5

你做这样的事情:

{{ dateObj | date:'shortDate' }}

或者

{{ dateObj | date:'ddmmy' }}

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


Pet*_*kiy 5

从 Angular 9 开始,本地化过程发生了变化。查看官方文档

请按照以下步骤操作:

  1. 如果还没有本地化包,请添加:ng add @angular/localize
  2. 正如文档中所说:

Angular 存储库包含常见区域设置。您可以通过在应用程序工作区配置文件 (angular.json) 的 sourceLocale 字段中设置源区域设置来更改应用程序的构建源区域设置。构建过程(在本指南中将翻译合并到应用程序中进行了描述)使用应用程序的 angular.json 文件自动设置 LOCALE_ID 令牌并加载区域设置数据。

因此,请像这样设置区域设置(可以在此处angular.json找到可用区域设置列表):

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "test-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "i18n": {
        "sourceLocale": "es"
      },
      ....
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          ...
          "configurations": {
            "production": {
             ...
            },
            "ru": {
              "localize": ["ru"]
            },
            "es": {
              "localize": ["es"]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "test-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "test-app:build:production"
            },
            "ru":{
              "browserTarget": "test-app:build:ru"
            },
            "es": {
              "browserTarget": "test-app:build:es"
            }
          }
        },
        ...
      }
    },
    ...
  "defaultProject": "test-app"
}
Run Code Online (Sandbox Code Playgroud)

基本上,您需要sourceLocalei18n部分中定义并添加具有特定语言环境的构建配置,例如"localize": ["es"]. 您可以选择将其添加到此serve部分

  1. build使用或构建具有特定区域设置的应用程序serveng serve --configuration=es