Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A Date.parse implementation from Stackoverflow stuffs.
// This is a slightly modified version of two patches. The first suggested at
// and the second, for Date.js suggested at
// 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 ={}, 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;

This comment has been minimized.

Copy link

adambutler commented May 14, 2014

@farmdawgnation 👍 thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.