Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Forked from netojoaobatista/Date.prototype.diff.js
Created September 2, 2019 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trfiladelfo/b195cc73f4fceedb50d0cfa4b2ffc911 to your computer and use it in GitHub Desktop.
Save trfiladelfo/b195cc73f4fceedb50d0cfa4b2ffc911 to your computer and use it in GitHub Desktop.
Returns the difference between two Date objects.
Object.defineProperty(Date.prototype,"diff",{
writable: false, configurable: false, enumerable: true,
/**
* Returns the difference between two Date objects.
* @param {Date} The date to compare to.
* @return {Object}
* @throws {TypeError}
*/
value: function(date) {
if (date instanceof Date){
var ms = this-date;
var diff = {};
for ( diff.years = 0; ms>=31536000000; diff.years++, ms -= 31536000000);
for ( diff.months = 0; ms>=2628000000; diff.months++, ms -= 2628000000);
for ( diff.days = 0; ms>=86400000; diff.days++, ms -= 86400000);
for ( diff.hours = 0; ms>=3600000; diff.hours++, ms -= 3600000);
for ( diff.minutes = 0; ms>=60000; diff.minutes++, ms -= 60000);
for ( diff.seconds = 0; ms>=1000; diff.seconds++, ms -= 1000);
diff.milliseconds = ms;
return diff;
}
throw new TypeError("invalid date");
}
});
var date = new Date("2012-04-26T17:05:14.000Z");
var diff = date.diff(new Date("2012-04-24T21:29:42.000Z"))
console.log(JSON.stringify(diff)); //{"years":0,"months":0,"days":1,"hours":19,"minutes":35,"seconds":32,"milliseconds":0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment