LoginSignup
3
3

More than 1 year has passed since last update.

[javascript]Dateで日付の比較をする時は日付のフォーマットに気をつけようという話

Last updated at Posted at 2022-12-28

多分出尽くしてるネタだとは思うけど、ハマったので備忘録として投稿。

あらすじ

以下のコードを実行したところ、

var currentDate = new Date('2022/12/01');

var startDate = new Date('2022-12-01');
var endDate = new Date('2022-12-31');

if (startDate <= currentDate && currentDate <= endDate) {
  alert('師走です')
} else {
  alert('師走じゃないです')
}

アラートに 師走じゃないです が出力された。
!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?

何故こんな動きになったか?

Chrome だと YYYY-MM-DD だと時間が9時間ずれる不具合があるみたいです。

console.log(new Date('2022-12-01')); // Thu Dec 01 2022 09:00:00 GMT+0900 (日本標準時)

ちなみにこれはChrome特有の不具合で、Firefox, IE 11 では再現しないようです。
https://kenzauros.com/blog/new-date-makes-wrong-date-with-javascript/
( 勝手に参照させていただきました。ありがとうございます :bow: )

対処方法

1: 日付のフォーマットを YYYY/MM/DD で統一する

var currentDate = new Date('2022/12/01');

var startDate = new Date('2022/12/01');
var endDate = new Date('2022/12/31');

if (startDate <= currentDate && currentDate <= endDate) {
  alert('師走です')
} else {
  alert('師走じゃないです')
}
  • 少なくとも Chrome Firefox IE 11 では問題なく動く
  • 他のブラウザでどう動くかわからないし上記ブラウザでも将来的に仕様が変わる可能性があるのでちょっと不安
    • MDN によると ISO 8601 形式を推奨してる模様(他のフォーマットだと各ブラウザでの挙動が保証されてないため)

2: ISO8601 フォーマットを使う

var currentDate = new Date('2022-12-01T00:00:00+09:00');

var startDate = new Date('2022-12-01T00:00:00+09:00');
var endDate = new Date('2022-12-31T00:00:00+09:00');

if (startDate <= currentDate && currentDate <= endDate) {
  alert('師走です')
} else {
  alert('師走じゃないです')
}
  • 国際規格なので、ブラウザ間での挙動の違いがないはず
  • JST前提で +09:00 決め打ちしたけど海外からのアクセスを想定する場合は適宜 +09:00 の変更が必要

js の Date は辛い :innocent:

3
3
2

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
3
3