Skip to content

Fast RFC 3339 date processing in javascript

by Topper on August 13th, 2009

UPDATE: This article is translated to Serbo-Croatianlanguage by Anja Skrba.

UPDATE: Removed dead Motionbox link. I work at Amicus now.

At Motionbox, we use a RFC 3339 time format in some data we return. Javascript doesn’t natively handle this format with Date.parse. The only other blog post I’ve seen on the subject is this:

http://dansnetwork.com/2008/11/01/javascript-iso8601rfc3339-date-parser/

However, since that’s a regular expression that’s parsing on the string, it can sometimes be slower (but not toooo bad… 1000 iterations on the code from the blog post above took < 100 miliseconds in IE7 (~40 miliseconds in Firefox on a macbook pro).

I knew we could do better with splits. With my code below I got it operating 60% faster (so operations take 40% of the time from the code above).

[js]
Date.prototype.setRFC3339 = function(dString){
var utcOffset, offsetSplitChar;
var offsetMultiplier = 1;
var dateTime = dString.split(“T”);
var date = dateTime[0].split(“-“);
var time = dateTime[1].split(“:”);
var offsetField = time[time.length - 1];
var offsetString;
offsetFieldIdentifier = offsetField.charAt(offsetField.length – 1);
if (offsetFieldIdentifier == “Z”) {
utcOffset = 0;
time[time.length - 1] = offsetField.substr(0, offsetField.length – 2);
} else {
if (offsetField[offsetField.length - 1].indexOf(“+”) != -1) {
offsetSplitChar = “+”;
offsetMultiplier = 1;
} else {
offsetSplitChar = “-“;
offsetMultiplier = -1;
}
offsetString = offsetField.split(offsetSplitChar);
time[time.length - 1] == offsetString[0];
offsetString = offsetString[1].split(“:”);
utcOffset = (offsetString[0] * 60) + offsetString[1];
utcOffset = utcOffset * 60 * 1000;
}

this.setTime(Date.UTC(date[0], date[1] – 1, date[2], time[0], time[1], time[2]) + (utcOffset * offsetMultiplier ));
return this;
};
[/js]

  • Disappointed

    Doesn’t seem to work. I get an error because it treats offsetField as an array and it’s just a string. Even after fixing that I get an invalid date time. :(

  • Anonymous

    @disappointed – we were using this in a production environment for a couple of years without problem. Do you have an example? Also – in Javascript, you can use strings as arrays (at least in the browsers).

  • http://twitter.com/thegoleffect Van Nguyen

    Line 22, is that supposed to be “=” or is it really just doing the comparison and skipping (“==”)”==”)

  • Kobydiego

    substr is faster than split (with fixed format)

  • kevin

    this is a big help for working with data coming out of gnip powertrack in the activitystream format. thanks!