Date.prototype.adjust
Friday, February 23, 2007I 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); - All the arguments are required, use 0 for no adjustments
- Use negative numbers to go back in time
- Year roll over is handled, for example if you add 15 months.
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
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.
Thanks for that Chris, sorry. Try the above code.
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.
That's right Geoff, it doesn't include timezone adjustment for DST. If it did the library would be about 20 times the size :)