The task described in the title of this post is one of those extremely annoying things that should be a 20 second ordeal, but instead it can consume hours of Googling and sometimes result in not so great solutions.
So basically we need to format a DateTime object encoded into JSON
to something that is human-readable and can be rendered on a page.
Dec 13 2013 22:42
Sounds simple enough.. A lot of one-liners would suggest the following:
While this works, the solution is not ideal as it strips off the timezone information. So to deal with this, you need to instantiate the object with the timezone offset present and hence substring(6) won’t cut it. One approach is to strip the slashes from the JSON datetime, and instantiate the new object:
var jsonDate = '/Date(1386974529007-0500)/'; var strippedDate = jsonDate.replace(/[\\/]/g, ""); var jsDate = eval("new " + strippedDate);
Obviously this can be a one-liner, I just split it up for readability.
If you are using ExtJS4.x, you can also do the following:
Ext.Date.format(Ext.Date.parseDate(jsonDate , "MS"), 'M j Y H:i')