はじめに
Angularにて日付を扱う機会が増えてきたのでまとめてみます。
ミスあるかと思います。ご指摘大歓迎です。
テンプレート(HTML)内で日付フォーマット
template で日付フォーマットを扱う場合、Angular標準パイプのDatePipe
を使用するのが一般的かと思います。
構文はdatetime | date:format
です。
format
は省略可能ですが、localeに関わらず日付の位置が固定化されてしまうため、できるだけフォーマット指定をおすすめします。
app.component.ts
export class AppComponent {
public now = new Date();
}
app.component.html
<div>現在時刻:{{now | date:"yy/MM/dd HH:mm"}}</div>
コンポーネント(component.ts)内での日付フォーマット
その1
Angular全バージョンで共通して使えるのは、@angular/common
にあるDatePipe
を使う方法です。
以下の手順で日付のフォーマットを行います。
- app.module.tsの
providers
にDatePipeを追加 - 使用したいコンポーネントにDIする
-
transform(date, format)
関数で日付をフォーマットする
app.module.ts
import { DatePipe } from '@angular/common';
@NgModule({
providers: [ DatePipe ] // 1
})
app.component.ts
import { DatePipe } from '@angular/common';
export class AppComponent {
constructor(
public datePipe: DatePipe // 2
) {
}
public alertNow() {
let now = new Date();
alert(this.datePipe.transform(now, "yy/MM/dd HH:mm")); // 3
}
}
その2
Angular6の場合、DatePipe
の関数を直接使うことができます。
※app.module.ts
の設定も不要です
app.component.ts
import { Component, OnInit, Inject, LOCALE_ID } from '@angular/core';
import { formatDate } from '@angular/common';
export class AppComponent {
constructor(
@Inject(LOCALE_ID) private locale: string
) {
}
public alertNow() {
let now = new Date();
alert(formatDate(now, "yy/MM/dd HH:mm", this.locale));
}
}
参考文献
StackOverFlow:Angular - Use pipes in services and components
Qiita:Angularのパイプをモデル内で使う