Fast RFC 3339 date processing in javascript
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
-
Anonymous
-
Van Nguyen
-
Kobydiego
-
kevin