Skip to content

Instantly share code, notes, and snippets.

@streadway
Created September 9, 2010 10:54
Show Gist options
  • Save streadway/571715 to your computer and use it in GitHub Desktop.
Save streadway/571715 to your computer and use it in GitHub Desktop.
function fromISO8601(str) {
var o = function(s) { return (s || '+') == '-' ? -1 : 1 } // Offset (pos/neg)
, i = function(s) { return s ? parseInt(s, 10) : 0; } // Integer (smart 0 handling)
, m = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)(?:[T ](\d\d):?(\d\d):?(\d\d)?(?:Z?([+-]?)(\d\d):?(\d\d)?)?)?/)
, d = new Date()
;
d.setUTCFullYear(i(m[1]));
d.setUTCMonth(i(m[2]));
d.setUTCDate(i(m[3]));
d.setUTCHours(i(m[4]) + o(m[7]) * i(m[8]));
d.setUTCMinutes(i(m[5]) + o(m[7]) * i(m[9]));
d.setUTCSeconds(i(m[6]));
return d;
}
console.log(fromISO8601("2010-09-09"));
console.log(fromISO8601("2010-09-09 12:34Z"));
console.log(fromISO8601("2010-09-09 12:34:01Z"));
console.log(fromISO8601("2010-09-09T12:34Z"));
console.log(fromISO8601("2010-09-09T12:34+01"));
console.log(fromISO8601("2010-09-09T12:34-01"));
console.log(fromISO8601("2010-09-09T12:34+0130"));
console.log(fromISO8601("2010-09-09T12:34+01:30"));
console.log(fromISO8601("2010-09-09T12:34-0130"));
console.log(fromISO8601("2010-09-09T12:34-01:30"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment