LoginSignup
0
1

More than 1 year has passed since last update.

`new Date('2023-04-06')` と `new Date('2023-04-06 00:00')` の違い

Posted at

この違いにすぐ答えれる人はJSチョットデキル人じゃないだろうか。
自分は初めて知った。

それぞれの出力は↓。

new Date(`2023-04-06`).toString()
// => 'Thu Apr 06 2023 09:00:00 GMT+0900 (Japan Standard Time)'
new Date(`2023-04-06 00:00`).toString()
// => 'Thu Apr 06 2023 00:00:00 GMT+0900 (Japan Standard Time)'

前者のほうは日本時間の午前9時を指している。どういうことか。

MDNには↓のように記載されている。

Date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local. You are therefore also advised to make sure the input format is consistent between the two types.

つまり、日付だけで時刻を省略すると、UTC扱いになるとのこと。
new Date('2023-01-01') はUTCの2023年1月1日の0時になるので、
JSTに変換すると午前9時になる。
時刻を省略しないと、各地域のローカルタイムになる。

Gatsbyをいじってるとしょっちゅう日付の操作が発生するんだけど、
この違いを分かってないとバグるので注意(1敗)。

例えば、「2023年の1月の記事を集めたいな〜」って思ったときに、
'2023-01-01' 以上 '2023-02-01' 以下といった指定はNG。
これだとUTCになるので、2023年1月1日のAM9時〜2023年2月1日のAM9時の期間が対象になってしまう。

このバグが発生してるGatsbyの拙作theme

こちら
今から治すので待って...待って...。

0
1
3

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
0
1