2016-01-20 110 views
84

我想顯示日期使用歐洲格式dd/mm/yyyy但使用DatePipe shortDate格式它只顯示使用美國日期樣式mm/dd/yyyy
我假設默認語言環境是en_US。也許我錯過了文檔,但我如何更改Angular2應用程序中的默認語言環境設置?或者,有沒有辦法將自定義格式傳遞給DatePipe?如何在Angular 2中設置DatePipe的區域設置?

+1

我想知道這一點。我發現日期管道文檔解釋了在格式字符串中y'm'和d's的順序被忽略,因爲順序是由區域設置的。但沒有跡象表明如何設置(甚至獲取)區域設置。 –

回答

188

由於Angular2 RC6,你可以設置默認的語言環境您的應用程序模塊中,加入了供應商:

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

的貨幣/日期/數字管道應該拿起的語言環境。 LOCALE_ID是從角度/核心導入的OpaqueToken

import { LOCALE_ID } from '@angular/core'; 

對於更高級的用例,您可能希望從服務中獲取語言環境。區域將被解決(一次)時創建使用日期管道元件:

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

希望它爲你工作。

+21

我很驚訝這還沒有出現在任何地方。不在日期管道頁面(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)。很棒的發現。 –

+0

另請參見:設置此語言環境似乎不會影響貨幣管道(Angular 2.0 final)。 –

+0

這是否也意味着我們可以使用HTTP請求獲取語言環境?不完全確定這是如何工作的。 – Hyperd

3

你做這樣的事情:

{{ dateObj | date:'shortDate' }}

{{ dateObj | date:'ddmmy' }}

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

+0

對不起,如果它不清楚我的問題,但這正是我做的,但模式'shortDate',它只顯示在美國風格。時間風格很好。 – nsbm

+0

第二個例子顯示了傳遞給DatePipe的格式,這就是你想要的嗎? – Langley

+0

嘗試過但它不起作用。獨立於日期顯示數字'5'。 – nsbm

12

我已經在date_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 」。

如果我錯了,請賜教。

+0

https://github.com/angular/angular/blob/master/modules/@angular/common/src/pipes/date_pipe.ts – julestruong

+0

你可能想看看下面的花冠的答案。這是更新,並提供了一個很好的解決方案。 –

3

我用同樣的問題掙扎,用這個

{{dateObj | date:'ydM'}} 

所以,我已經嘗試瞭解決方法,而不是最好的解決辦法,我沒有工作,但它的工作:

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

我總是可以創建一個自定義管道。

0

複製谷歌管改變了語言環境,它適用於我的國家它是可能的,他們沒有完成它的所有語言環境。以下是代碼。

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); } 
} 
23

如果您想爲您的應用程序設置一次語言,那麼帶有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); 
    } 

} 

如果你改變使用TranslateService應用程序的顯示語言(見ngx-translate

this.translateService.use('en'); 

你的應用程序中的格式應該自動被更新。使用

例子:

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

或檢查我的簡單的 「注意事項」 的項目here

enter image description here

+0

我得到模板解析錯誤;無法編譯過濾器'localizedDate' 我以與建議相同的方式使用。 –

+0

您是否正確聲明瞭LocalizedDatePipe?請參閱我的[示例項目](https://github.com/milanhlinak/notes/blob/master/notes-ui/src/app/shared/pipes/pipes.module.ts)中的pipe.module.ts。 –

+0

是的,我早些時候已經解決了,@Milan Hlinak,當時我應該回答我的評論。但無論如何感謝您的及時迴應。你做得很好。 –

1

對於AOT那些有問題的,你需要做的是有點不同了useFactory:

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

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

作爲angular5,你可以在提供者數組中使用一個胖箭頭表達式 – iuliust

+0

'{提供:LOCALE_ID,useFactory:()=>'fr-CA'}'爲我做了詭計;) – JoxieMedina

0

好吧,我提出這個解決方案很簡單,使用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); 
    } 

} 
5

With angular5上述答案不再有效!

下面的代碼:

app.module.ts

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

引出以下錯誤:

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

隨着angular5你必須加載和註冊使用的語言環境文件在你自己的。

app.module.ts

import { NgModule, LOCALE_ID } from '@angular/core'; 
import { registerLocaleData } from '@angular/common'; 
import lcoaleDeAt from '@angular/common/locales/de-at'; 

registerLocaleData(lcoaleDeAt); 

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

Documentation

+0

確實如果您需要使用除en-US之外的其他語言環境,則應該註冊它。謝謝你的回答,@ zgue – MikkaRin