LoginSignup
0
0

More than 3 years have passed since last update.

AngularでUnixTimestampをフォーマットするPipe

Last updated at Posted at 2019-05-05

AngularのPipeでUnixTimestampを日本の日付フォーマットに変換するシンプルなPipeを作成する

以下のコマンドでPipeを作成します。Cli便利ですね。

ng g pipe ConvertTimeStampToDate

内容はこんな感じ。いたってシンプルです。

  1. Dateオブジェクトを作る
  2. それぞれyearやmonthやhourやminute(0埋めする)を切り出して文字列で返す
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'convertTimeStampToDate'
})
export class ConvertTimeStampToDatePipe implements PipeTransform {

  transform(timeStamp: number): string {
    const formatedDate = new Date(timeStamp * 1000);

    /** 月 */
    const month = formatedDate.getMonth() + 1;

    /** 日を0埋め */
    const day = ('0' + formatedDate.getMinutes()).slice(-2);

    return formatedDate.getFullYear() + '' + month + '' + formatedDate.getDate() + '' + formatedDate.getHours() + ':' + day;
  }

}

入出力結果

入力


{{timestampValue | convertTimeStampToDate}}
1556694104(=timestampValueの値)

出力

2019年5月1日16:01
0
0
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
0
0