LoginSignup
6
3

More than 3 years have passed since last update.

【Javascript】 Timestamp を yyyy/MM/dd HH:mm:ss 形式で 時刻に変換する

Last updated at Posted at 2020-05-25

コード

timestampToTime.js
// 引数 timestamp の単位はミリ秒であるとする
const timestampToTime = (timestamp) => {
  const date = new Date(timestamp * 1000);
  const yyyy = `${date.getFullYear()}`;
  // .slice(-2)で文字列中の末尾の2文字を取得する
  // `0${date.getHoge()}`.slice(-2) と書くことで0埋めをする
  const MM = `0${date.getMonth() + 1}`.slice(-2); // getMonth()の返り値は0が基点
  const dd = `0${date.getDate()}`.slice(-2);
  const HH = `0${date.getHours()}`.slice(-2);
  const mm = `0${date.getMinutes()}`.slice(-2);
  const ss = `0${date.getSeconds()}`.slice(-2);

  return `${yyyy}/${MM}/${dd} ${HH}:${mm}:${ss}`;
}

timestamp = 100000000; // 1億
console.log(timestampToTime(timestamp));

実行

node timestampToTime.js

実行結果

1973/03/03 18:46:40

参考サイト

6
3
1

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
6
3