Wednesday, July 15, 2009

The Fastest Date toJSON and fromJSON?

I know yesterday post supposed to be the last 'till the the end of the month but I could not resits. Dustin Diaz twitted

anyone trying to parse our wonky rails dates in JS. do this: var date = Date.parse(str.replace(/( \+)/, ' UTC$1')); seems to fix it.

Again, I could not resist to create a toUTCString based function to create JSON strings and to parse them back. This is the result and apparently is both the fastest implementation I know and cross browser (Chrome, Firefox, Inernet Explorer, Safari).
This is a quick post so if you find some problem please let me know, thanks.

(function(){
// WebReflection Fast Date.prototype.toJSON and Date.fromJSON Suggestion
var rd = /^.{5}(\d{1,2}).(.{3}).(.{4}).(.{2}).(.{2}).(.{2}).+$/,
rs = /^(.{4}).(.{2}).(.{2}).(.{2}).(.{2}).(.{2}).+$/,
d = new Date,
f = /(GMT|UTC)$/.exec(d.toUTCString())[1], // cheers gazheyes
m = {},
i = 0,
s = ""
;
d.setUTCDate(1);
while(i < 12){
d.setUTCMonth(i);
m[s = /^.{5}(\d{1,2}).(.{3})/.exec(d.toUTCString())[2]] = ++i < 10 ? "0" + i : i;
m[m[s]] = s;
};
Date.prototype.toJSON = function(){
var e = rd.exec(this.toUTCString());
return e[3].concat("-", m[e[2]], "-", e[1], "T", e[4], ":", e[5], ":", e[6], "Z");
};
try{Date.fromJSON(d.toJSON());
Date.fromJSON = function(s){
var e = rs.exec(s);
return new Date(Date.parse(e[2].concat(" ", e[3], " ", e[1], " ", e[4], ":", e[5], ":", e[6], " ", f)));
};
}catch(e){
Date.fromJSON = function(s){
var e = rs.exec(s);
return new Date(Date.parse(e[3].concat(" ", m[e[2]], " ", e[1], " ", e[4], ":", e[5], ":", e[6], " ", f)));
};
}
})();

Basically everything is a shortcut and I am using only native methods ... is there anything faster except probably a substr based one?

No comments:

Post a Comment