tags:

views:

161

answers:

4

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.

+3  A: 

Try something like this:

 var d = new Date("08/18/2009");
 d.setDate(d.getDate()-5);
Stephen Wrighton
+3  A: 

It goes something like this:

var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
Chris Nielsen
+2  A: 
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:

http://simonwillison.net/2007/Dec/3/datejs/

karim79
it's an edge case, but this can fail around the start/end of daylight saving time. you're not subtracting 5 days, but 5*24 hours. the first day of daylight saving time is only 23 hours long, and the last is 25 hours long. it usually doesn't matter, but it's something to consider.
Kip
@Kip - Interesting, I missed that nuance entirely.
karim79
A: 

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;

Joshua
What happens if you add for example 50 days to a date this way? Will it set the date to 68 August 2009? Or are you sure that this always wraps over to the appropriate month and/or year correctly?
Jesper
it always raps correctly. Try it :D
Joshua