2020年之后的JavaScript月错误

时间:2018-07-29 14:42:41

标签: javascript date

如果我输入2020年之后的年份,谁能告诉我为什么是3月而不是2月? 在Windows 10,Chrome和Edge上进行了测试

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

控制台日志的结果...

  

2021年3月23日星期二22:38:13 GMT + 0800(新加坡标准时间)

以下显示了正确的月份...

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

结果是

  

2025年2月19日星期三23:15:30 GMT + 0800(新加坡标准时间)

请注意:如果我使用的年份是 2020年或以下,则返回值正确。答案需要对此进行解释...

1 个答案:

答案 0 :(得分:2)

只需扩展注释(“ 2020是a年,它是2月29日。(我假设您今天在7月29日测试此代码)”),并带有示例代码: / p>

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);

加上指定重复项(JavaScript Date Bug February 2014)的内容。