Last active
August 29, 2015 13:56
-
-
Save farmdawgnation/8887962 to your computer and use it in GitHub Desktop.
A Date.parse implementation from Stackoverflow stuffs.
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
// This is a slightly modified version of two patches. The first suggested at | |
// http://stackoverflow.com/questions/5802461/javascript-which-browsers-support-parsing-of-iso-8601-date-string-with-date-par | |
// and the second, for Date.js suggested at | |
// http://stackoverflow.com/questions/12145437/date-js-parsing-an-iso-8601-utc-date-incorrectly | |
// | |
// Here we override the implementation of Date.parse provided by Date.js. In this implementation we | |
// first check to see if we can construct the date using the Date constructor. If we can, we move | |
// along. If we cannot, we attempt to start the Date.js grammar parser. If that, too, fails us, we | |
// then assume we're running in IE 8, and someone passed in an ISO8601 string, which IE8's date | |
// constructor won't recognize. So we try to manually parse it out, returning a Date instance. | |
// | |
// This code is licensed under CC-BY-SA, as pretty much all of it came from StackOverflow. | |
Date.parse = function (dateString) { | |
var date, time, r = null; | |
if (! dateString) | |
return null; | |
if (dateString instanceof Date) | |
return dateString; | |
date = new Date(Date._parse(dateString)); | |
time = date.getTime(); | |
// The following will be FALSE if time is NaN which happens if date is an Invalid Date | |
// (yes, invalid dates are still date objects. Go figure.) | |
if (time === time) | |
return date; | |
// try our grammar parser | |
try { | |
r = Date.Grammar.start.call({}, dateString.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1")); | |
} catch (e) { | |
return null; | |
} | |
var grammarParserResult = ((r[1].length === 0) ? r[0] : null); | |
if (grammarParserResult !== null) | |
return grammarParserResult; | |
// The Grammar parser and date constructor failed. That means we were passed an | |
// ISO 8601 string that doesn't compute using the date constructor likely because | |
// we're in freaking IE 8. Our last ditch effort is to try and parse the 8601 date | |
// manually. | |
var parts = dateString.match(/\d+/g); | |
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]); | |
var isoDate = new Date(isoTime); | |
return isoDate; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@farmdawgnation 👍 thanks