Wednesday 4 November 2015

Get Difference between two dates in JavaScript

Hi,

Dealing with dates will always dicey. Most of the times when we calculate difference between two dates we don't consider a Daylight saving change.

In this case, the date on which day light saving change happens will have a duration in milliseconds which != 1000*60*60*24, so the typical calculation will fail.

A more accurate way to get the number of days between two JavaScript dates can be written as follows:

// date1 and date2 are javascript Date objects
function dateDiffInDays(date1, date2) {
    var vInt_MS_PER_DAY = 1000 * 60 * 60 * 24;
    // Discard the time and time-zone information.
    var utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
    var utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
    return Math.floor((utc2 - utc1) / vInt_MS_PER_DAY);
}

Hope this helps.

--
Happy Coding
Gopinath


 

1 comment: