Skip to content

Instantly share code, notes, and snippets.

@felipecwb
Last active August 29, 2015 14:14
Show Gist options
  • Save felipecwb/c272863af0ea39613c2b to your computer and use it in GitHub Desktop.
Save felipecwb/c272863af0ea39613c2b to your computer and use it in GitHub Desktop.
compare between Dates
(function () {
/**
* compare date, return 0 = equals, 1 = date1 > date2, -1 = date1 < date2
* @param {String} date1 string in W3C format (Y-m-d\TH:i:sP)
* @param {String} date2 string in W3C format (Y-m-d\TH:i:sP)
* @return {int|bool} false if dates are invalid, 0 = equals, 1 = date1 > date2, -1 = date1 < date2
*/
Date.compare = function (date1, date2) {
if (! (date1 instanceof Date)) {
date1 = new Date(date1);
}
if (! (date2 instanceof Date)) {
date2 = new Date(date2);
}
date1 = +date1;
date2 = +date2;
if (isNaN(date1) || isNaN(date2)) {
return false;
}
return (date1 > date2)-(date1 < date2);
}
})();
// with Date
console.log(Date.compare(new Date('2015-02-04'), new Date('2015-02-04'))); // 0
console.log(Date.compare(new Date('2015-02-01'), new Date('2015-02-04'))); // -1
console.log(Date.compare(new Date('2015-02-10'), new Date('2015-02-04'))); // 1
// with String
console.log(Date.compare('2015-02-04T20:50:30', '2015-02-04T20:50:30')); // 0
console.log(Date.compare('2015-02-04T19:50:30', '2015-02-04T21:50:30')); // -1
console.log(Date.compare('2015-02-04T20:50:30', '2015-02-04T19:50:30')); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment