LoginSignup
0
1

More than 3 years have passed since last update.

JsでUnixタイムスタンプを取得する

Last updated at Posted at 2021-03-06

JavascriptでUnixタイムスタンプを取得する

firebaseを使うにあたってタイムスタンプ変換を学習したので備忘録的に残すことにしました。

Unixタイムスタンプとは

UTCで1970年1月1日 00:00 からの経過時間のこと
単位は秒数

タイムスタンプを取得する

現在時刻のタイムスタンプを取得

console.log((new Date().getTime())/ 1000 ); 

指定した時間のタイムスタンプを取得

let d = new Date(2000,3,1,10,30).getTime()); 
//getTime()ではミリ秒で取得されるので、1000で割ります
console.log(Math.floor( d / 1000 ));

逆にUnixタイムスタンプからDate型へ

const dateTime = new Date(timestamp * 1000)

momentを使用して楽に取得・変換を行う

// 取得
moment().unix() 

// 変換
moment.unix(timestamp).format()
0
1
2

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
1