Updated (bug fix): 2-11-09
In need of a JavaScript function that would parse an ISO8601 compliant date, I came across an attempt (http://delete.me.uk/2005/03/iso8601.html) and rewrote it (because I'm all about reinventing the wheel). My function extends the Date object and allows you to pass in an ISO8601 date (2008-11-01T20:39:57.78-06:00). The function will then return the Date. In the date string argument the dashes and colons are optional. The decimal point for milliseconds is mandatory (although specifying milliseconds isn't). If a timezone offset is specified, the '+' or '-' sign must be included. This function should also work with iCalendar(RFC2445) formatted dates. If a the date string doesn't match the format, there will be a final attempt to parse it with the built in Date.parse() method.
Code:
Date.prototype.setISO8601 = function(dString){ var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))/; if (dString.toString().match(new RegExp(regexp))) { var d = dString.match(new RegExp(regexp)); var offset = 0; this.setUTCDate(1); this.setUTCFullYear(parseInt(d[1],10)); this.setUTCMonth(parseInt(d[3],10) - 1); this.setUTCDate(parseInt(d[5],10)); this.setUTCHours(parseInt(d[7],10)); this.setUTCMinutes(parseInt(d[9],10)); this.setUTCSeconds(parseInt(d[11],10)); if (d[12]) this.setUTCMilliseconds(parseFloat(d[12]) * 1000); else this.setUTCMilliseconds(0); if (d[13] != 'Z') { offset = (d[15] * 60) + parseInt(d[17],10); offset *= ((d[14] == '-') ? -1 : 1); this.setTime(this.getTime() - offset * 60 * 1000); } } else { this.setTime(Date.parse(dString)); } return this; };
Usage:
var today = new Date(); today.setISO8601('2008-12-19T16:39:57.67Z');