Javascript DateDiff

Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).

EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!

//Set the two dates
var currentTime   = new Date()
var currDate      = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.

//currDate = 8/17/12 and iniPastedDate = 8/7/12

function DateDiff(date1, date2) {
    var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
    return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value      
}

//Write out the returning value should be using this example equal -10 which means 
//it has passed by ten days. If its positive the date is coming +10.    
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...

Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields NaN.

The second trry has no closing ). Apart from that, you're calling getTime on strings. You'd need to use new Date(...).getTime(). Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.


function setDateWeek(setDay){
    var d = new Date();
    d.setDate(d.getDate() - setDay); // <-- add this
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();
    return curr_date + "-" + curr_month + "-" + curr_year;
}


setDateWeek(1);