Skip to content

Instantly share code, notes, and snippets.

@benhinman
Created December 4, 2016 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benhinman/c8ebe9ca5170cadc50db1ab42057c88a to your computer and use it in GitHub Desktop.
Save benhinman/c8ebe9ca5170cadc50db1ab42057c88a to your computer and use it in GitHub Desktop.
This gist allows you to parse an ISO 8601 subset date in JavaScript. This method could be used in a JSON reviver function to inflate date strings into date objects.
!function () {
var isoDateFormat = /^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(?:(Z(?=$)|(?:\+|\-)(?=\d{2}:\d{2}))(?:(\d{2}):(\d{2}))?)?)?)?)?$/;
Date.parseIsoDate = function (isoDate, convertToBrowserTimeZone) {
/// <summary>
/// Parses an ISO date.
/// </summary>
/// <param name="isoDate">The ISO date to parse.</param>
/// <param name="convertToBrowserTimeZone" optional="true">Whether or not to convert the date to the browser's time zone (true by default).</param>
/// <returns>A date.</returns>
/// <remarks>
/// This method adheres to the standard noted here: http://www.w3.org/TR/NOTE-datetime.
/// In addition to the standard, this method also supports dates without time zone information.
/// Such dates are assumed to be in the browser's time zone.
/// </remarks>
// convert to the browser's time zone unless otherwise specified
convertToBrowserTimeZone = typeof convertToBrowserTimeZone !== "boolean" ? true : convertToBrowserTimeZone;
// parse date
var isoDateMatch = isoDateFormat.exec(isoDate);
if (!isoDateMatch) throw "Invalid date specified.";
// get date components
var fullYear = +isoDateMatch[1];
var month = (+(isoDateMatch[2] || 1) - 1);
var day = +(isoDateMatch[3] || 1);
var hours = +(isoDateMatch[4] || 0);
var minutes = +(isoDateMatch[5] || 0);
var seconds = +(isoDateMatch[6] || 0);
var milliseconds = Math.round((+(isoDateMatch[7] || 0)) * 1000);
// get minutes offset
var minutesOffset = isoDateMatch[8] && isoDateMatch[8] !== "Z" ? ((+isoDateMatch[9]) * 60) + (+isoDateMatch[10]) : 0;
if (isoDateMatch[8] === "-") {
minutesOffset = 0 - minutesOffset;
}
// create and return date
var setMethodPrefix = "set";
if (convertToBrowserTimeZone && isoDateMatch[8]) {
setMethodPrefix += "UTC";
minutes -= minutesOffset;
}
var date = new Date(0);
date[setMethodPrefix + "FullYear"](fullYear, month, day);
date[setMethodPrefix + "Hours"](hours, minutes, seconds, milliseconds);
return date;
};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment