AngularのPipeでUnixTimestampを日本の日付フォーマットに変換するシンプルなPipeを作成する
以下のコマンドでPipeを作成します。Cli便利ですね。
ng g pipe ConvertTimeStampToDate
内容はこんな感じ。いたってシンプルです。
- Dateオブジェクトを作る
- それぞれ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