0
0

More than 3 years have passed since last update.

【JavaScript】日付の操作いろいろ

Posted at

日時を取得

  //現在日時を取得
const d = new Date();

  //西暦を取得
d.getFullYear(); //2020

  //現在の月を取得(0から始まるので注意。1月は0になる)
d.getMonth(); //5

  //現在の日を取得
d.getDate(); //13

  //現在の曜日を取得
d.getDay();

  //時間を取得
d.getHours(); //0~23

  //分を取得
d.getMinutes(); //0~59

  //秒を取得
d.getSeconds(); //0~59

  //現在の日時を取得して何月何日と表示
const d = new Date();
  //getMonth()は0から始まるので+1する
console.log(`${d.getMonth() + 1}${d.getDate()}日`)
// 実行結果
// 5月13日

特定の日時を扱う

  //引数に年月日などを渡す。年と月は必須であとは省略すると日付に関しては 1 、時刻は 0 としてデータを作ってくれる
  //下記のようにすると、月は 0 から始まるので 2020 (年) 5 (月) 01 (日) 00 (時) 00 (分) 00 (秒)になる。
const birthday = new Date(2020,4);

 //指定された月の日を設定
birthday.setDate(31);  //2020 (年) 5 (月) 31 (日) 00 (時) 00 (分) 00 (秒)

  //指定された日の「時」を設定
birthday.setHours(10,20,30); //2020 (年) 5 (月) 31 (日) 10 (時) 20 (分) 30 (秒)

  //指定された日時の7日前を設定して定数に代入
const countdown = birthday.setDate(birthday.getDate() - 7);  //2020 (年) 5 (月) 24 (日) 10 (時) 20 (分) 30 (秒)

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