Skip to content

Instantly share code, notes, and snippets.

@remino
Created January 5, 2012 06:07
Show Gist options
  • Save remino/1563963 to your computer and use it in GitHub Desktop.
Save remino/1563963 to your computer and use it in GitHub Desktop.
JavaScript: DateDiff & DateMeasure: Calculate days, hours, minutes, seconds between two Dates
(function() {
function DateDiff(date1, date2) {
this.days = null;
this.hours = null;
this.minutes = null;
this.seconds = null;
this.date1 = date1;
this.date2 = date2;
this.init();
}
DateDiff.prototype.init = function() {
var data = new DateMeasure(this.date1 - this.date2);
this.days = data.days;
this.hours = data.hours;
this.minutes = data.minutes;
this.seconds = data.seconds;
};
function DateMeasure(ms) {
var d, h, m, s;
s = Math.floor(ms / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
this.days = d;
this.hours = h;
this.minutes = m;
this.seconds = s;
};
Date.diff = function(date1, date2) {
return new DateDiff(date1, date2);
};
Date.prototype.diff = function(date2) {
return new DateDiff(this, date2);
};
})();
@remino
Copy link
Author

remino commented Jan 5, 2012

If this is too much for you, try the convertMS() function: https://gist.github.com/1563878

@lashisu
Copy link

lashisu commented Aug 21, 2014

Hey Remino,

Nice function. But How can we get the difference between two date & time in hh:mm?

Suppose we have two date time like "2014-09-01|18:20:00" & "2014-09-02|20:00:00".

Here difference is 25:40 (25 Hours & 40 Minutes)

Can you please provide the function for the same.

Thanks,
Sushil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment