Last active
August 29, 2015 14:14
-
-
Save felipecwb/c272863af0ea39613c2b to your computer and use it in GitHub Desktop.
compare between Dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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