AngularのDatePipeのlocaleを変更したい場合(タイムゾーンを変更したい場合、も)

(Angular v.4.3.6を利用)

起動時にlocaleを設定 (JIT)

@NgModule({
  imports: [
    BrowserModule,
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    {
      provide: LOCALE_ID,
      useValue: navigator.language
      // useValue: 'ja'
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

動的にlocaleを変更

@Pipe({
  name: 'date'
})
export class DatePipeProxy implements PipeTransform {
  constructor(private localizationService: LocalizationService) {
  }
  public transform(value: any, pattern: string = 'mediumDate'): any {
    const ngPipe = new DatePipe(this.localizationService.locale);
    return ngPipe.transform(value, pattern);
  }
}

タイムゾーンを変更

  • 直接Intl.DateTimeFormatを利用するPipeをつくる
    • DateTimeFormatOptionstimeZoneを設定
    • DatePipeの内部でもDateTimeFormatを利用しているが、現状だとtimeZoneを変更するAPIはない

参考Url