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


 

One thought on “Get Difference between two dates in JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s