Skip to content

Instantly share code, notes, and snippets.

@mikelheim
Created February 19, 2014 07:34
Show Gist options
  • Select an option

  • Save mikelheim/9087604 to your computer and use it in GitHub Desktop.

Select an option

Save mikelheim/9087604 to your computer and use it in GitHub Desktop.
JavaScript function to set ISO date format reliably for across browsers. Resolves a problem with ie8 javascript date parser: http://stackoverflow.com/questions/12305039/net-webapi-iso-datetime-and-ie8
/**Parses string formatted as YYYY-MM-DDThh:mm:ss.sZ
* or YYYY-MM-DDThh:mm:ssZ (for IE8), to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DDThh:mm:ss.sZ,
* or YYYY-MM-DDThh:mm:ssZ - Zulu (UTC) Time Only,
* with year in range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d).*Z\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if (parts) {
month = +parts[2];
date.setUTCFullYear(parts[1], month - 1, parts[3]);
date.setUTCHours(parts[4]);
date.setUTCMinutes(parts[5]);
date.setUTCSeconds(parts[6]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment