在 JavaScript 中添加一周到日期:舍入误差还是夏令时?
我试图向数据对象添加 7 天,但是在某个阶段我开始得到奇怪的结果。
var currDate = new Date(2011, 2, 28)
, oldTicks = currDate.getTime()
, newTicks = oldTicks + (86400000 * 7)
, nextWeek = new Date(newTicks)
console.log('Old ticks: ' + oldTicks)
console.log('New ticks: ' + newTicks)
console.log('New date : ' + nextWeek)
我得到的输出,Chrome/FF 都是:
Old ticks: 1301230800000
New ticks: 1301835600000
log: New date : Sun Apr 03 2011 23:00:00 GMT+1000 (EST)
预期得到:
log: New date : Mon Apr 04 2011 23:00:00 GMT+1000 (EST)
如您所见,不是添加 7 天,而是只添加了 6 天。不过,上面的代码适用于其他日期,例如 2011 年 4 月 28 日或 2011 年 5 月 28 日。
I am trying to add seven days to a Data object, however at some stage I start getting strange results.
var currDate = new Date(2011, 2, 28)
, oldTicks = currDate.getTime()
, newTicks = oldTicks + (86400000 * 7)
, nextWeek = new Date(newTicks)
console.log('Old ticks: ' + oldTicks)
console.log('New ticks: ' + newTicks)
console.log('New date : ' + nextWeek)
The output I get, both Chrome/FF is:
Old ticks: 1301230800000
New ticks: 1301835600000
log: New date : Sun Apr 03 2011 23:00:00 GMT+1000 (EST)
Expected to get:
log: New date : Mon Apr 04 2011 23:00:00 GMT+1000 (EST)
As you can see, instead of adding 7 days, just 6 were added. The code above, however, works fine with other dates, say 2011 Apr 28 or 2011 May 28.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的推断,Crescent Fresh 是正确的。
查找时区
GMT+1000 (EST)
看起来像澳大利亚东部标准时间 - 来自 wikipedia - 按 UTC 偏移量列出的时区列表以及来自 wikipedia - 世界各地的日列表节约时间,显示澳大利亚在 OP 指定的日期范围之间从标准时间切换到夏令时。
Crescent Fresh is correct form what I can deduce.
Looking up timezones
GMT+1000 (EST)
looks like Australia Eastern Standard Time - from wikipedia - list of timezones by UTC offsetAnd from wikipedia - daylist savings time around the world, shows that Australia switches from standard to daylight savings time in between the date ranges specified by the OP.
如果是我,我会这样做:
对一天中的时间进行一些可能的调整。
也就是说,当我在 Chrome 开发者控制台中尝试您的代码时,我得到的答案是 4 月 4 日。
If it were me I'd do:
with some possible adjustments for time of day.
That said, when I try your code in my Chrome developer console, I get 04 Apr as the answer.