Date.prototype.adjust

Friday, February 23, 2007

I thought someone might find this useful: the Date.prorotype.adjust() function for adjusting a javascript date. It allows you to create a date object and then increment or decrement the years, months, days, hours, minutes or seconds easily: d.adjust(years, months, days, hours, minutes, seconds). [Update] OIK! Bone-headed bug fixed. Corrected code below.

Usage:

var d = new Date();
d.adjust(years, months, days, hours, minutes, seconds);

For example, this code will adjust a date 3 months and 5 days into the future:

var d = new Date();
d.adjust(0, 3, 5, 0, 0, 0);

And here's the simple but useful code:

Date.prototype.adjust = function(yr,mn,dy,hr,mi,se) {
var m,t;
this.setYear(this.getFullYear() + yr);
m = this.getMonth() + mn;
if(m != 0) this.setYear(this.getFullYear() + Math.floor(m/12));
if(m < 0) {
this.setMonth(12 + (m%12));
} else if(m > 0) {
this.setMonth(m%12);
}
t = this.getTime();
t += (dy * 86400000);
t += (hr * 3600000);
t += (mi * 60000);
t += (se * 1000);
this.setTime(t);
}

4 Comments

#1
On the February 24, 2007, Chris Hayward wrote:

Hi,
Your Date.adjust method is just what I needed. However, I have found that it doesn't seem to give correct results for a negative month value e.g try -2 for the month.
I can't quite see where the problem lies though. Let me know if you have a fix.
Much appreciated.

#2
On the February 24, 2007, Andrew Tetlaw wrote:

Thanks for that Chris, sorry. Try the above code.

#3
On the March 7, 2007, geoff wrote:

I think that this is not going to account for daylight savings. 
If I add 5 days, I expect it to be the same hour, just 5 days in the future.

#4
On the March 7, 2007, Andrew Tetlaw wrote:

That's right Geoff, it doesn't include timezone adjustment for DST. If it did the library would be about 20 times the size :)

Random outings from a chaotic mind

The Dexagogo Rocket Australian Web Industry Association logo

Delicious

Twitter