Dateオブジェクト
Dateオブジェクトは、
日付を操作するための主要なオブジェクトです。
構文
let date = new Date();
これで変数dateは、現在の時刻
(秒、分、時など)を内部に保持する日付オブジェクトとなります。
特別な関数を使用して、現在の時間、現在の日、
現在の月など、必要な時間の特性を取得することができます。
例えば、現在の時間はdate.getHours()で、
現在の月はdate.getMonth()で取得できます。
すべてのオプションを見てみましょう:
let date = new Date();
console.log(date.getSeconds()); // 秒
console.log(date.getMinutes()); // 分
console.log(date.getHours()); // 時
console.log(date.getDate()); // 日
console.log(date.getMonth()); // 月(0から開始)
console.log(date.getFullYear()); // 年
console.log(date.getDay()); // 現在の曜日
特定の時点を設定する
現在の時点ではなく、指定した時点を設定することができます。
そのためには、new Date(年, 月, 日, 時, 分, 秒, ミリ秒)の形式で
パラメータを渡します。この場合、変数dateには
現在の時刻ではなく、パラメータで指定した時刻が記録されます。
この形式の特徴:月のカウントは0から始まり、
時以降の省略されたパラメータは0と見なされ、
年、月、日については1と見なされます。
例
現在の日、月、年を
'年-月-日'の形式で出力してみましょう
(月の番号は0から始まるため、実際の月より1少なくなります):
let date = new Date();
let str = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
console.log(str);
関連項目
-
Dateオブジェクトに適用される主なメソッド:
getFullYear,getMonth,getDate,getHours,getMinutes,getSeconds,getDay,getTime