JavaScript Dateオブジェクト
先日、JSでカレンダープログラム(コマンドラインでcal
を叩いたときと同じもの)を作成しました。
その際、Date
を使ったのですが罠が多かったので記録として残そうと思います。
Dateオブジェクトについて
Dateを使うことで特定の年月や日付、時刻を取得することができる。
例えば、今日の日付が欲しかったら、以下のようにする。
const now = new Date() console.log(now.getDate()) // => 4
具体的な使い方
現在の時刻がほしい
- 現在の時刻が欲しい場合、Dateをnewするときは引数に何も渡さない(上の例と同じ)
const now = new Date() // => Wed Nov 04 2020 20:13:39 GMT+0900 (日本標準時)
GMT = Greenwich Mean Time = グリニッジ標準時。
日本から送った E メールなどの送信日時に [ GMT +09:00 ]と表示されていることがありますが、これはグリニッジ標準時から 9 時間進んでいる、という意味になります。
特定の時刻がほしい
Dateをnewするときに引数を渡すことで、特定の時刻を取得できる。
Dateのコンストラクタ関数(new)は渡すデータ型や引数によって時刻の指定方法が変わる。
Dateは次の3種類を引数としてサポートしている。
- 時刻を示す文字列を渡すもの
const date1 = new Date('Wed Nov 04 2020 20:13:39') // => Wed Nov 04 2020 20:13:39 GMT+0900 (日本標準時) const date2 = new Date('2020/12/31) // => Thu Dec 31 2020 00:00:00 GMT+0900 (日本標準時) // 他にも引数の取り方はある
- 時刻の部分(年・月・日など)をそれぞれ数値で渡すもの
new Date(year, month, day, hour, minutes, seconds, milliseconds);
(日を表す第三引数から後ろの引数は省略可能)
const date1 = new Date(2020, 11, 4, 20, 13, 39) // => Fri Dec 04 2020 20:13:39 GMT+0900 (日本標準時) const date2 = new Date(2020, 12, 31) // => Sun Jan 31 2021 00:00:00 GMT+0900 (日本標準時)
- 時刻値(1970-01-01 00:00:00(UTC)からの秒数(ミリ秒単位))を渡すもの
const date1 = new Date(1612018886000) // => Sun Jan 31 2021 00:01:26 GMT+0900 (日本標準時)
GMT を調整して、世界共通の標準時と定めたのが、UTC = Universal Time, Coordinated = 協定世界時。
なんでも GMT をそのまま世界の基準として使ってしまうと、長い目で見ると微妙なズレ(100 年で約 18 秒)が生じるため、人工的に調整する必要があったのだとか
メソッド
- date.getFullYear()
- date.getMonth()
- date.getDate()
- date.getDay() (曜日を表す。0〜6を日曜日から土曜日に当てはめている。)
- date.getHours()
- date.getMinutes()
- date.getSeconds()
- date.getMilliseconds()
- date.getTime() (時刻値(1970-01-01 00:00:00(UTC)からの秒数(ミリ秒単位))
const now = new Date() console.log(now) // => Wed Nov 04 2020 21:10:36 GMT+0900 (日本標準時) console.log(now.getFullYear()) // => 2020 console.log(now.getMonth()) // => 10 console.log(now.getDate()) // => 4 console.log(now.getDay()) // => 3 (水曜日なので3) console.log(now.getHours()) // => 21 console.log(now.getMinutes()) // => 10 console.log(now.getSeconds()) // => 36 console.log(now.getMilliseconds()) // => 269 console.log(now.getTime()) // => 1604491836269
罠
上記の結果を見るとgetMonth()
が10
となっている
これは、月を表す第二引数は0から11までの数値で指定するから!
月末日の取得
月末日がほしい場合、月を+1して、日を0にする
例えば、2020年の2月の月末日は
const date = new Date(2020, 2, 0) console.log(date.getDate()) // => 29
日にちの0を入れたときの月は正確に取得できないかも?
const date = new Date(2020, 2, 0) console.log(date.getFullYear()) // => 2020 console.log(date.getMonth()) // => 1 (なぜか1月になる) console.log(date.getDate()) // => 29
参考