Hi,
does anybody know of an easy way or taking a date (e.g. today) and going back X days?
So, for example, if I want to calculate the date 5 days before today?
Any help would really be appreciated.
Hi,
does anybody know of an easy way or taking a date (e.g. today) and going back X days?
So, for example, if I want to calculate the date 5 days before today?
Any help would really be appreciated.
Try something like this:
var d = new Date("08/18/2009");
d.setDate(d.getDate()-5);
It goes something like this:
var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);
If you're performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:
split your date into parts, then return a new Date with the adjusted values
function DateAdd(date, type, amount){
var y = date.getFullYear(),
m = date.getMonth(),
d = date.getDate();
if(type === 'y'){
y += amount;
};
if(type === 'm'){
m += amount;
};
if(type === 'd'){
d += amount;
};
return new Date(y, m, d);
}
Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;