IT박스

Angular 2의 DatePipe에서 로캘을 설정하는 방법은 무엇입니까?

itboxs 2020. 7. 16. 19:47
반응형

Angular 2의 DatePipe에서 로캘을 설정하는 방법은 무엇입니까?


유럽 ​​형식을 사용하여 날짜를 표시하고 싶지만 dd/mm/yyyyDatePipe shortDate 형식을 사용하면 미국 날짜 스타일 만 사용하여 표시됩니다 mm/dd/yyyy.
기본 로케일이 en_US라고 가정합니다. 어쩌면 문서에서 누락되었지만 Angular2 앱에서 기본 로캘 설정을 어떻게 변경할 수 있습니까? 또는 DatePipe에 사용자 지정 형식을 전달하는 방법이 있습니까?


Angular2 RC6부터 공급자를 추가하여 앱 모듈에서 기본 로캘을 설정할 수 있습니다.

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

Currency / Date / Number 파이프는 로캘을 선택해야합니다. 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
}

그것이 당신을 위해 작동하기를 바랍니다.


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>

또는 간단한 "메모"프로젝트를 여기에서 확인 하십시오 .

여기에 이미지 설명을 입력하십시오


angular5위의 대답은 더 이상 작동합니다!

다음 코드 :

app.module.ts

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

다음과 같은 오류가 발생합니다.

오류 : "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...
  ]
})

선적 서류 비치


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'로 하드 코딩되어 있음을 나타냅니다.

내가 틀렸다면 나를 깨우쳐주세요.


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

그런 다음 파이프를 동적으로 사용하십시오.

myComponent.component.html

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

myComponent.component.ts

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

app.module.ts에서 다음 가져 오기를 추가하십시오. LOCALE 옵션 목록이 여기에 있습니다 .

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

그런 다음 공급자를 추가하십시오.

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

Use pipes in html. Here is the angular documentation for this.

{{ dateObject | date: 'medium' }}

You do something like this:

{{ dateObj | date:'shortDate' }}

or

{{ dateObj | date:'ddmmy' }}

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


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.


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

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

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

Copied the google pipe changed the locale and it works for my country it is posible they didnt finish it for all locales. Below is the code.

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

Ok, I propose this solution, very simple, using 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);
  }

}

This might be a little bit late, but in my case (angular 6), I created a simple pipe on top of DatePipe, something like this:

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

May not be the best solution, but simple and works.

참고 URL : https://stackoverflow.com/questions/34904683/how-to-set-locale-in-datepipe-in-angular-2

반응형