Skip to content

Instantly share code, notes, and snippets.

@andyearnshaw
Created May 2, 2013 14:19
Show Gist options
  • Save andyearnshaw/5502514 to your computer and use it in GitHub Desktop.
Save andyearnshaw/5502514 to your computer and use it in GitHub Desktop.
Simple date diff in JavaScript. The ones I found out there were using division and modulus and would not represent 28 days between Feb and March as 1 month. None of them took into account daylight savings either.
/**
* Returns an object with properties representing the number of years, months, days, hours, minutes
* and seconds between the `this` date and a passed date or Date.now
*/
Object.defineProperty(Date.prototype, 'diff', {
writable: true,
configurable: true,
value: function (/*[ instanceof Date || instanceof Number ]*/) {
var diff = new Date(),
op = arguments[0] == null ? new Date() : new Date(arguments[0]),
abs = !!arguments[typeof arguments[1] === 'undefined' ? 0 : 1];
if (isNaN(op) || isNaN(this))
throw new Error ('Tried to diff an invalid date.');
var p = this > op,
d1 = p ? this : op,
d2 = p ? op : this,
y = d1.getUTCFullYear() - d2.getUTCFullYear(),
m = d1.getUTCMonth() - d2.getUTCMonth(),
d = d1.getUTCDate() - d2.getUTCDate(),
h = d1.getUTCHours() - d2.getUTCHours(),
i = d1.getUTCMinutes() - d2.getUTCMinutes(),
s = d1.getUTCSeconds() - d2.getUTCSeconds();
if (s < 0)
s = 60 + s,
i--;
if (i < 0)
i = 60 + i,
h--;
if (h < 0)
h = 24 + h,
d--;
if (d < 0)
d = (new Date(d1.getUTCFullYear(), d1.getUTCMonth(), 0).getUTCDate()) + d,
m--;
if (m < 0)
m = 12 + m,
y--;
return {
isPast: p,
years: y,
months: m,
days: d,
hours: h,
mins: i,
secs: s
};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment