LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】現在時刻を取得する

Last updated at Posted at 2022-01-13

割と使うけど忘れやすいので、JavaScriptで現在時刻を取得する方法を備忘録としてメモしておく。

sample.js
const date = new Date(); //現在時刻を取得
const y = date.getFullYear(), //西暦年
      m = date.getMonth() + 1, //月 
      d = date.getDate(), //日
      H = date.getHours(), //時
      M = date.getMinutes(), //分
      S = date.getSeconds(); //秒

console.log(y,m,d,H,M,S); //例 2022 1 14 3 10 30

他にもミリ秒を取得するなどもある。

あとは使う形式に応じて色々と整形する。

sample.js
`${y}/${m}/${d}`; //例 2022/1/14
`${H}:${M}:${S}`; //例 3:10:30

0paddingなどと組み合わせると 2022/01/14 03:10:30などの表記もできる。

sample.js
const m_pad = ( '00' + m ).slice( -2 ); //'00'とsliceの中身は桁数に応じて増減させる。今は2桁表示にさせたいので0は二つ、sliceの中は-2。
console.log(m_pad); //例 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