Last active
August 29, 2015 14:20
-
-
Save felipecwb/7d29340ec5653629c59a to your computer and use it in GitHub Desktop.
Improvement of JS date compare
This file contains hidden or 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 () { | |
| "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