0

Can anyone tell me why the month is March instead of Feb, if I enter a year after 2020? Tested on Windows 10, Chrome & Edge

  const date = new Date()
  date.setFullYear("2021")
  date.setMonth("1") // February
  date.setDate("23")
  console.log(date)

The result of console log...

Tue Mar 23 2021 22:38:13 GMT+0800 (Singapore Standard Time)

The following shows the correct month though...

var event = new Date('August 19, 2025 23:15:30');
event.setMonth(1);
console.log(event);

Result is

Wed Feb 19 2025 23:15:30 GMT+0800 (Singapore Standard Time)

Please Note: If I use year 2020 or below, the return values are correct. The answer needs to explain this anamoly...

5
  • my date is 23rd, not 29th, but strangely, setting the date first works... if you submit answer I can mark it as answered
    – Aaron Gong
    Commented Jul 29, 2018 at 14:47
  • 3
    Possible duplicate of JavaScript Date Bug February 2014 Commented Jul 29, 2018 at 14:47
  • It does not explain why it works for year 2020
    – Aaron Gong
    Commented Jul 29, 2018 at 14:53
  • 1
    2020 is a leap year, it has 29th of February. (I assume you are testing this code today, 29th of July)
    – tevemadar
    Commented Jul 29, 2018 at 15:01
  • 1
    Crikey, set it all in one go: d.setFullYear(2021, 1, 23). :-)
    – RobG
    Commented Jul 30, 2018 at 3:57

1 Answer 1

2

Just to extend the comment ("2020 is a leap year, it has 29th of February. (I assume you are testing this code today, 29th of July)") with example code:

function test29(year){
  var date=new Date();
  date.setDate(29); // "emulate" today, 29th of something
  
  date.setFullYear(year);
  date.setMonth(1);
  date.setDate(23);
  console.log(date);
}
console.log("test29 is affected by leap years:");
test29(2019);
test29(2020);
test29(2021);
function test19(year){
  var date=new Date();
  date.setDate(19); // "emulate" a 19th of something
  
  date.setFullYear(year);
  date.setMonth(1);
  date.setDate(23);
  console.log(date);
}
console.log("test19 is not affected by leap years:");
test19(2019);
test19(2020);
test19(2021);

Plus what the pointed duplicate (JavaScript Date Bug February 2014) writes.

Not the answer you're looking for? Browse other questions tagged or ask your own question.