Dateオブジェクト

Dateオブジェクトは日時を扱うオブジェクトで、Dateコンストラクターから生成します。

new Date()と引数を与えない場合は、現在の日時が取得できます。

文字列を引数にすることができ、2023-01-01のような形式で記述することで、その文字列を指定した文字列のDateオブジェクトを生成することができます。

数値を引数にする場合は、年、月、日、時間、、、のように順番に渡すことで生成することができます。

数値を引数に渡す場合の注意点として、月は0始まりですので、0を渡した場合は、1月11を渡した場合は12月のようになります。

index.js◎
...
console.log('a,b,c,d'.split(',')); // ['a', 'b', 'c', 'd']
const now = new Date();
console.log(now); // 現在日時
const date1 = new Date('2023-01-01');
console.log(date1);  // Sun Jan 01 2023 09:00:00 GMT+0900 (日本標準時)
const date2 = new Date(2023, 3, 1);
console.log(date2);  // Sat Apr 01 2023 00:00:00 GMT+0900 (日本標準時)

date.getFullYear(),date.getMonth(),date2.getDate(),date2.getDay()で、年、月、日、曜日を取得することができます。曜日に関しては、日曜日は0、土曜日が6となります。

index.js◎
...
console.log(date2);  // Sat Apr 01 2023 00:00:00 GMT+0900 (日本標準時)
console.log(date2.getFullYear()); // 2023
console.log(date2.getMonth()); // 3
console.log(date2.getDate()); // 1
console.log(date2.getDay()); // 6

その他にどういったメソッドがあるか気になる方は、以下サイトを見ていただければと思います。

Last updated