Skip to content

Instantly share code, notes, and snippets.

@felipecwb
Last active August 29, 2015 14:20
Show Gist options
  • Save felipecwb/7d29340ec5653629c59a to your computer and use it in GitHub Desktop.
Save felipecwb/7d29340ec5653629c59a to your computer and use it in GitHub Desktop.
Improvement of JS date compare
(function () {
"use strict";
/**
* Compare dates.
* @param {Date|String} date instance or string in W3C format
* @throws TypeError
* @return {int} 0 = equals, -1 = gt, 1 = lt
*/
Date.prototype.compare = function (date) {
if (! (date instanceof Date)) {
date = new Date(date);
}
if (date.toString() === "Invalid Date") {
throw TypeError();
}
return (+this > +date)-(+this < +date);
};
})();
var date = new Date('2015-02-04');
console.log(date.compare('2015-02-04')); // 0
console.log(date.compare('2015-02-10')); // -1
console.log(date.compare('2015-02-01')); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment