Calculating Date Ranges using Javascript?

I’m fairly new to programming in Javascript and quite frankly find it difficult (an old COBOL programmer). My question is this, are their any functions in Javascript that are similar to the VB.Net “DateDiff” function? If not, are their any free code snippets that will calculate the range of days and/or months between 2 date values?

Thanks!

You can use the js Date object to get information about different dates and make comparisons. Here is an example function that would return the difference in days/months for you using the date object:



// Compare older vs newer dates
function dateDiff(older,newer) {
    var data= {};

    // Elapsed milliseconds
    data.elapsed = newer.getTime() - older.getTime();

    // Elapsed Days
    data.days = Math.round((((data.elapsed/1000)/60)/60)/24);

    // Elapsed Months
    var monthDiff = (newer.getMonth()+1) - (older.getMonth()+1);
    var yearDiff = newer.getFullYear() - older.getFullYear();
    data.months = monthDiff + (yearDiff*12);

    // Return data
    return data;
}

// Compare the date 1st Feb 2010 with Now and alert the number of days and months elapsed
var diff = dateDiff(new Date("1 Feb 2010"),new Date());
alert("Days: " + diff.days);
alert("Months: " + diff.months);

You can even compare dates objects directly without using the date object functions, I think using the functions is a little more readable. More info about the js date object: http://www.w3schools.com/js/js_obj_date.asp