Skip to content

Instantly share code, notes, and snippets.

@fredyang
Created October 3, 2014 21:46
Show Gist options
  • Save fredyang/02f381725fee190ba5ce to your computer and use it in GitHub Desktop.
Save fredyang/02f381725fee190ba5ce to your computer and use it in GitHub Desktop.
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8061_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4] || 0) - tzHour,
int(match[5] || 0) - tzMin,
int(match[6] || 0),
int(match[7] || 0));
return date;
}
return string;
}
function int(str) {
return parseInt(str, 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment