LoginSignup
0
1

More than 3 years have passed since last update.

GAS Date 2月だけに起こるバグ

Last updated at Posted at 2021-01-31

条件

GAS で 下記のコード

target = new Date('4:00:00 AM');

とすると

Sat Dec 30 1899 10:00:00 GMT+0900 (Japan Standard Time) {}

と解釈される
2月1日に

const now = new Date();
target.setFullYear(now.getFullYear());
target.setMonth(now.getMonth());
target.setDate(now.getDate());

すると

target.setFullYear(2021);
target.setMonth(1); // 0から始まるので 1は2月
target.setDate(1);

と実行される

期待値

これを実行すると

Mon Feb 01 2021 10:00:00 GMT+0900 (Japan Standard Time)

となって欲しい

発生した事象

しかし実際にこれを実行すると

Mon Mar 01 2021 10:00:00 GMT+0900 (Japan Standard Time)

あれ?

原因

target.setFullYear(2021);
// Thu Dec 30 2021 10:00:00 GMT+0900 (Japan Standard Time) 単純に年が2021となる
target.setMonth(1);
//Tue Mar 02 2021 10:00:00 GMT+0900 (Japan Standard Time)  2月30日つまり 3月2日と解釈される
target.setDate(1)
//Mon Mar 01 2021 10:00:00 GMT+0900 (Japan Standard Time) 3月2日 の"日"の部分が 1になる

なるほどなるほど 2月だけ30日がないから
今まで問題なかったけど 本来は 日付を30->1にしないと 正しく動かないのか

解決策

const now = new Date();
target.setFullYear(now.getFullYear());
target.setMonth(now.getMonth(),1); //日付を30->1にする
target.setDate(now.getDate());
0
1
1

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