最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

date - Javascript setHours(1) not working for Mar 27 2011 01:00:00 GMT+0100 - Stack Overflow

programmeradmin0浏览0评论

I'm totally confused as of why this is not working?

I'm iterating through a date range and just add 1 hour step by step. This worked fine until this week. Basically until the date hits Mar 27 2011 01:00:00 GMT+0100. Then it just stucks and does not add anything. If I add +3h then it works again, but not with +1.

I'm using Firebug on Firefox and also tried it in the console.

Sun Mar 27 2011 01:00:00 GMT+0100

>>> this.setHours(0);
1301180400000
>>> this.setHours(1);
1301184000000
>>> this.setHours(2);
1301184000000
>>> this.setHours(3);
1301187600000

This is the code:

Date.prototype.addHours = function (h) {
    this.setHours(this.getHours() + h);
    return this;
}

I have the same bug in Safari and Chrome.

I'm totally confused as of why this is not working?

I'm iterating through a date range and just add 1 hour step by step. This worked fine until this week. Basically until the date hits Mar 27 2011 01:00:00 GMT+0100. Then it just stucks and does not add anything. If I add +3h then it works again, but not with +1.

I'm using Firebug on Firefox and also tried it in the console.

Sun Mar 27 2011 01:00:00 GMT+0100

>>> this.setHours(0);
1301180400000
>>> this.setHours(1);
1301184000000
>>> this.setHours(2);
1301184000000
>>> this.setHours(3);
1301187600000

This is the code:

Date.prototype.addHours = function (h) {
    this.setHours(this.getHours() + h);
    return this;
}

I have the same bug in Safari and Chrome.

Share Improve this question asked Mar 22, 2011 at 12:26 RemyRemy 12.7k14 gold badges65 silver badges106 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 6

Daylight Saving Time causing this behavior. 27 March is the day DST starts.

Edit:

Hope this solves your problem: Daylight Saving in JavaScript

Just a guess: Could it be related to Daylight Savings time?

I know this question is quite old, but just in case someone else hits this problem, using UTC methods you can avoid this behaviour:

Date.prototype.addHours = function (h) {
    this.setUTCHours(this.getUTCHours() + h);
    return this;
}

I got the same problem as you and resolved it with

Date.prototype.addHours = function (h) {
    this = new Date(this.getTime() + h*3600000);
    return this;
}

I'm not sure if creating a new Date object is a good idea but it works for me.

发布评论

评论列表(0)

  1. 暂无评论