Javascript RFC 3999 parser

2007-12-11

I couldn't find a relevant script that parses a rfc 3999 timestamp. Javascript can only parse a very specific date but RSS et al uses the 3999 timestamp. I would prefer a different timestamp altogether, but that wouldn't change much for Javascript.

I converted my php parser (php has the same problem, if you can't use strptime(), which I can't). The function expects a string and returns a unix timestamp, or 0 if the string did not match the regex.

A 3999 timestamp has the following variations:
1985-04-12T23:20:50.52Z
1985-04-12t23:20:50.52Z
1985-04-12T23:20:50.52z
1985-04-12T23:20:50.52+01:00
1985-04-12T23:20:50.52-01:00

Code: (JS)
function parseRFC3999(time) {
var t = 0;
var r = '^([0-9]{4})-([0-9]{2})-([0-9]{2})[TtZz ]{1}([0-9]{2}):([0-9]{2}):([0-9]{2})[0-9.]*([+-0-9]{3}|[Zz]{1})(.)*$';
var re = new RegExp(r);
var match = re.exec(time);
if (match[7] == 'Z' || match[7] == 'z' ) match[7] = 0; // the magic Z indicates GMT
if (match != null && match.length > 0) {
// Matches magic numbers are equal to () parts in the regex (y m d h m s tz)
// Months offset at 0, not 1 :@
// Also, dont forget the radix for parseInt, or it will parse zero
// prefixed values as octal (which returns 0 for 08 and 09)
t = new Date(parseInt(match[1], 10), parseInt(match[2], 10) -1, parseInt(match[3], 10), (parseInt(match[4], 10) + parseInt(match[7], 10)), parseInt(match[5], 10), parseInt(match[6], 10));
}
return t.getTime();
}


PS. The :( smileys in the regex are : ( without a space... can't help that at the moment.