【问题标题】:please explain my error in this javascript date math请解释我在这个 javascript 日期数学中的错误
【发布时间】:2017-10-06 19:48:23
【问题描述】:

这是 Visual Studio 即时窗口的输出。我从mondaysDate 开始,创建第二个日期thisDate,然后使用 mondaysDate 作为基数添加整数。

我不明白为什么将日期加 3 会产生 11 月 2 日,而将日期加 4 会产生 12 月 4 日。

多次调用 setDate() 是否违法?

?mondaysDate
Mon Oct 30 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

?thisDate
Mon Oct 30 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

?thisDate.setDate(mondaysDate.getDate() + 3)
1509595200000
?thisDate
Thu Nov 02 2017 00:00:00 GMT-0400 (Eastern Daylight Time)


?thisDate.setDate(mondaysDate.getDate() + 4)
1512363600000
?thisDate
Mon Dec 04 2017 00:00:00 GMT-0500 (Eastern Standard Time)

?mondaysDate
Mon Oct 30 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

【问题讨论】:

  • 当你说date + 3时,你的意思是加3天、3个月、3年吗?
  • 我假设它正在增加天数:stackoverflow.com/questions/3818193/…
  • 你期望的结果是什么?
  • 我预计是 11 月 3 日而不是 12 月 4 日。

标签: javascript date-math


【解决方案1】:

问题是您第一次从 10 月 1 日添加 33 days,然后从 11 月 1 日添加 34 days

thisDate.setDate(mondaysDate.getDate() + 3)
// You set the date to 30 + 3 (33) days from the first day of the current month (Oct 1)
// Oct 1 + 33 days = Nov 2
// thisDate = Thu Nov 02 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

thisDate.setDate(mondaysDate.getDate() + 4)
// You set the date to 30 + 4 (34) days from the first day of the current month (Nov 1)
// Nov 1 + 34 days = Dec 4
// thisDate = Mon Dec 04 2017 00:00:00 GMT-0500 (Eastern Standard Time)

日期是相对于thisDate 设置的,从当月的 1 日开始,并在mondaysDate + 4 天中加上天数。每次拨打setDate,都会更新thisDate

您可以在MDN 上阅读有关 setDate 的更多信息。

【讨论】:

  • 第一次通话为什么不加33天?
  • @Patrick Evans:如果是在 10 月 30 日加上 33 天,为什么会显示为 11 月 2 日?
  • @Tim,检查 Cristy 附加的 MDN 链接。 The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
猜你喜欢
  • 2015-02-25
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2010-10-10
相关资源
最近更新 更多