【问题标题】:Why does new Date(2018,12, 25) give the wrong month and year? [duplicate]为什么 new Date(2018,12, 25) 给出错误的月份和年份? [复制]
【发布时间】:2019-01-03 22:58:37
【问题描述】:

我完全不知道为什么以下代码在 2019 年 1 月 3 日当天执行此代码时给了我 2021 年...什么...我错过了什么...我非常需要我想坐在我旁边的编码伙伴.. >.

function daysTillChristmas()
{
  var today = new Date();
  var christmasDay1 = new Date(today.getFullYear() +1, 12, 25);
  var test = today.getFullYear() + 1;
  var christmasDay2 = new Date(2020, 12, 25);

  console.log(today);
  console.log("Today: " + today);
  console.log("Today Full Year: " + today.getFullYear());
  console.log("ChristmasDay1: " + christmasDay1);
  console.log(christmasDay2);
  console.log("ChristmasDay2: " + christmasDay2);
  console.log("Test: " + test);
}

我的输出是……

"2019-01-03T22:54:33.294Z"
Today: Thu Jan 03 2019 14:54:33 GMT-0800 (Pacific Standard Time)
Today Full Year: 2019
ChristmasDay1: Mon Jan 25 2021 00:00:00 GMT-0800 (Pacific Standard Time)
"2021-01-25T08:00:00.000Z"
ChristmasDay2: Mon Jan 25 2021 00:00:00 GMT-0800 (Pacific Standard Time)
Test: 2020

顺便说一句...我目前正在学习 Javascript,我正在使用以下 URL 来测试代码并进行一些练习。

浏览器:Chrome 70.0.3538.77 32 位

https://www.w3resource.com/javascript-exercises/javascript-basic-exercises.php#EDITOR

【问题讨论】:

标签: javascript date


【解决方案1】:

见MDN:

注意:参数 monthIndex 是从 0 开始的。这意味着一月 = 0,十二月 = 11。

所以月份 12 是一年中的第 13 个月,它会翻转并成为下一年的一月。

【讨论】:

  • /facepalm 我确实记得...该死...谢谢...>.>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 2014-05-10
  • 1970-01-01
  • 2013-09-13
  • 2023-02-23
相关资源
最近更新 更多