LoginSignup
4

More than 3 years have passed since last update.

JavaScriptでnew Date()で日付と時刻を取得する

Posted at

プログラミング勉強日記

2020年9月27日
JSでnew Date()を使って現在の日付・時刻を取得する方法をまとめる。

基本的な使い方

 以下のようにnew Date()で現在の日付・時刻する。

var nowDate = new Date();
console.log(nowDate);
コンソール結果
Sun Sep 27 2020 09:22:20 GMT+0900 (日本標準時)

〇〇年〇月〇日を表示する

 2020年9月27日を表示するためには、getFullYear(), getMonth(), getDate()を使う。getMonth()は1月が0、2月が1となるので、getMonth()+1とする。

var nowDate = new Date();
var year = nowDate.getFullYear();
var month = nowDate.getMonth()+1;
var date = nowDate.getDate();

var today = year + '' + month + '' + date + '';
console.log(today);
コンソール結果
2020年9月27日

曜日を取得する

 曜日の取得にはgetDay()を使う。getDay()は日曜が0、月曜が1と返ってくる。

var nowDate = new Date();
var year = nowDate.getFullYear();
var month = nowDate.getMonth()+1;
var date = nowDate.getDate();

/* 曜日追加 */
var day_array = ['','','','','','','']
var day = day_array[now.getDay()];

var today = year + '' + month + '' + date + '' + '' + day + '';
console.log(today);
コンソール結果
2020年9月27日(日)

参考文献

new Date()で現在の日付・時刻を取得する【JavaScript】

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
4