Function to Parse a Microsoft JSON DateTime returned from a WCF service in JavaScript
When a DateTime is converted to JSON in a WCF Web service (WebHttp in this particular case) it's semi-difficult to convert that to something we can use when we return the date to a client via JavaScript. For example:
"LastPlayed":"\/Date(1278187099000-0400)\/"
After almost an hour of research and goofing around with this, I've come up with the following, which seems to work just fine on Internet Explorer 8, Firefox 3.6, and Chrome 5.0.
function parseMicrosoftJsonDateTime(content) {
try {
content = content.replace(/\//g, '');
var contentDate = eval('new ' + content);
return contentDate.toDateString() + ' ' + contentDate.toTimeString();
} catch (ex) {
return content;
}
}
As you can see if it fails at any point I just return whatever was passed. Otherwise since the only thing bothering us are the two /s, I'm first removing all of those. Then I'm creating a new variable, which ends up call new Date(x). This date variable can then be converted to a string via standard JavaScript functionality.
There may be a better way to handle this, but this is fairly quick, and works just as I need it to.
Sample outputs
Internet Explorer 8: Sat Jul 3 2010 14:58:18 CDT
Chrome 5.0 and Firefox 3.6: Sat Jul 03 2010 14:58:18 GMT-0500 (Central Daylight Time)
Search
Links of Note
Support This Site
If my blog was helpful to you, then please consider visiting my Amazon Wishlist.