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

Javascript 如何在Angular 2中设置DatePipe中的区域设置?,javascript,angular,date-pipe,Javascript,Angular,Date Pipe,我想使用欧洲格式显示日期,但使用DatePipeshortDate格式仅使用美国日期样式MM/dd/yyyy。 我假设默认的语言环境是en_US。也许文档中缺少了我,但是如何更改Angular2应用程序中的默认区域设置?或者,是否有某种方法可以将自定义格式传递给DatePipe?您可以执行以下操作: private _regionSub: Subscription; private _localeId: string; constructor(private _datePipe: DateP

我想使用欧洲格式显示日期,但使用DatePipeshortDate格式仅使用美国日期样式
MM/dd/yyyy


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

您可以执行以下操作:

private _regionSub: Subscription;
private _localeId: string;

constructor(private _datePipe: DatePipe, private _store: Store<any>) {
  this._localeId = 'en-AU';
  this._regionSub = this._store.pipe(select(selectLocaleId))
    .subscribe((localeId: string) => {
      this._localeId = localeId || 'en-AU';
    });
}

ngOnDestroy() { // Unsubscribe }

transform(value: string | number, format?: string): string {
  const dateFormat = format || getLocaleDateFormat(this._localeId, FormatWidth.Short);
  return this._datePipe.transform(value, dateFormat, undefined, this._localeId);
}
{{dateObj|date:'shortDate'}}

{{dateObj|date:'ddmmy'}}

见:

我已经查看了date\u pipe.ts,它有两个有趣的信息。 顶部附近有以下两行:

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

return DateFormatter.format(value, defaultLocale, pattern);
这对我来说意味着日期管道目前被硬编码为“en-US”


如果我错了,请告诉我。

我也在为同样的问题苦苦挣扎,但没有用这个为我工作

{{dateObj | date:'ydM'}}
因此,我尝试了一种变通方法,虽然不是最好的解决方案,但它奏效了:

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

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

复制了google管道,更改了区域设置,它适用于我的国家,可能他们没有完成所有区域设置。下面是代码

import {
    isDate,
    isNumber,
    isPresent,
    Date,
    DateWrapper,
    CONST,
    isBlank,
    FunctionWrapper
} from 'angular2/src/facade/lang';
import {DateFormatter} from 'angular2/src/facade/intl';
import {PipeTransform, WrappedValue, Pipe, Injectable} from 'angular2/core';
import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection';


var defaultLocale: string = 'hr';

@CONST()
@Pipe({ name: 'mydate', pure: true })
@Injectable()
export class DatetimeTempPipe implements PipeTransform {
    /** @internal */
    static _ALIASES: { [key: string]: String } = {
        'medium': 'yMMMdjms',
        'short': 'yMdjm',
        'fullDate': 'yMMMMEEEEd',
        'longDate': 'yMMMMd',
        'mediumDate': 'yMMMd',
        'shortDate': 'yMd',
        'mediumTime': 'jms',
        'shortTime': 'jm'
    };


    transform(value: any, args: any[]): string {
        if (isBlank(value)) return null;

        if (!this.supports(value)) {
            console.log("DOES NOT SUPPORT THIS DUEYE ERROR");
        }

        var pattern: string = isPresent(args) && args.length > 0 ? args[0] : 'mediumDate';
        if (isNumber(value)) {
            value = DateWrapper.fromMillis(value);
        }
        if (StringMapWrapper.contains(DatetimeTempPipe._ALIASES, pattern)) {
            pattern = <string>StringMapWrapper.get(DatetimeTempPipe._ALIASES, pattern);
        }
        return DateFormatter.format(value, defaultLocale, pattern);
    }

    supports(obj: any): boolean { return isDate(obj) || isNumber(obj); }
}
导入{
isDate,
isNumber,
我现在,
日期,
日期包装器,
康斯特,
我是空白的,
函数包装器
}来自“angular2/src/facade/lang”;
从'angular2/src/facade/intl'导入{DateFormatter};
从'angular2/core'导入{PipeTransform,WrappedValue,Pipe,Injectable};
从'angular2/src/facade/collection'导入{StringMapWrapper,ListWrapper};
var defaultLocale:string='hr';
@常数()
@管道({name:'mydate',pure:true})
@可注射()
导出类DatetimeTempPipe实现PipeTransform{
/**@内部*/
静态_别名:{[key:string]:string}={
“中等”:“yMMMdjms”,
‘short’:‘yMdjm’,
“fullDate”:“yMMMMEEEEd”,
“longDate”:“yMMMMd”,
“mediumDate”:“yMMMd”,
“短日期”:“yMd”,
“mediumTime”:“jms”,
“短时”:“jm”
};
转换(值:any,参数:any[]):字符串{
if(isBlank(value))返回null;
如果(!this.supports(值)){
log(“不支持此DUEYE错误”);
}
变量模式:string=isPresent(args)和&args.length>0?args[0]:'mediumDate';
if(isNumber(值)){
值=DateWrapper.fromMillis(值);
}
if(StringMapWrapper.contains(DatetimeTempPipe.\u别名,模式)){
pattern=StringMapWrapper.get(DatetimeTempPipe.\u别名,pattern);
}
return DateFormatter.format(值、默认语言环境、模式);
}
支持(obj:any):布尔{return isDate(obj)| | isNumber(obj);}
}

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

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
    //otherProviders...
  ]
})
货币/日期/编号管道应选择区域设置。LOCALE_ID是从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
}

希望它能为您工作。

如果您想为应用程序设置一次语言,那么使用LOCALE\u 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更改应用程序显示语言(请参阅)

应用程序中的格式应自动更新

使用示例:

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

{{'note.updated于{date:note.updatedAt}本地化日期:'fullDate'}}

或者检查我的简单“注释”项目


对于那些AOT有问题的用户,您需要使用useFactory进行稍微不同的操作:

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

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

好的,我提出这个解决方案,非常简单,使用
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);
  }

}

使用
angular5
上述答案不再有效

以下代码:

app.module.ts

导致以下错误:

错误:缺少区域设置“de at”的区域设置数据


使用
angular5
时,您必须自己加载并注册使用的区域设置文件

app.module.ts


这可能有点晚了,但在我的例子(angular 6)中,我在DatePipe上创建了一个简单的管道,类似于:

private _regionSub: Subscription;
private _localeId: string;

constructor(private _datePipe: DatePipe, private _store: Store<any>) {
  this._localeId = 'en-AU';
  this._regionSub = this._store.pipe(select(selectLocaleId))
    .subscribe((localeId: string) => {
      this._localeId = localeId || 'en-AU';
    });
}

ngOnDestroy() { // Unsubscribe }

transform(value: string | number, format?: string): string {
  const dateFormat = format || getLocaleDateFormat(this._localeId, FormatWidth.Short);
  return this._datePipe.transform(value, dateFormat, undefined, this._localeId);
}
private\u regionSub:订阅;
private _localeId:string;
构造函数(private\u datePipe:datePipe,private\u store:store){
这个._localeId='en AU';
this.\u regionSub=this.\u store.pipe(选择(selectLocaleId))
.subscribe((localeId:string)=>{
这个;
});
}
Ngondestory(){//Unsubscribe}
转换(值:字符串|数字,格式?:字符串):字符串{
const dateFormat=format | | getLocaleDateFormat(this._localeId,FormatWidth.Short);
返回此._datePipe.transform(值、日期格式、未定义、此._localeId);
}

可能不是最好的解决方案,但简单有效。

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

然后添加提供者

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "es-ES" }, //your locale
  ]
})
在html中使用管道。这是这个的角度

{{ dateObject | date: 'medium' }}

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

首先,声明您在应用程序中使用的区域设置,例如在
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');
}
然后,动态使用管道:

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

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

从角度9开始,定位过程发生了变化。退房

按照以下步骤操作:

  • 如果还没有本地化包,请添加它:
    ng Add@angular/localize
  • 正如文件中所说:
  • 角度回购
    import localeIt from '@angular/common/locales/it';
    import localeEnGb from '@angular/common/locales/en-GB';
    .
    .
    .
    ngOnInit() {
        registerLocaleData(localeIt, 'it-IT');
        registerLocaleData(localeEnGb, 'en-GB');
    }
    
    <span>{{ dueDate | date: 'shortDate' : '' : translateService.currentLang }}</span>
    
     constructor(public translateService: TranslateService) { ... }
    
    {
      "$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"
    }