LoginSignup
22
14

More than 5 years have passed since last update.

Angular 日付のフォーマット

Posted at

はじめに

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を使う方法です。
以下の手順で日付のフォーマットを行います。
1. app.module.tsのprovidersにDatePipeを追加
2. 使用したいコンポーネントにDIする
3. 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のパイプをモデル内で使う

22
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
14