Remy
Remy

Reputation: 12693

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

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.

Upvotes: 3

Views: 2135

Answers (4)

Eduard Martinez
Eduard Martinez

Reputation: 21

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

Upvotes: 2

Erico Chan
Erico Chan

Reputation: 1170

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.

Upvotes: 1

Kerem Baydoğan
Kerem Baydoğan

Reputation: 10722

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

Edit:

Hope this solves your problem: Daylight Saving in JavaScript

Upvotes: 6

Athena
Athena

Reputation: 3178

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

Upvotes: 2

Related Questions