I'm working on JavaScript and stuck in a small issue.
I am receiving this date in JSON response 1322919399447-0500
and I want to format this like: 6:50 PM, Dec 3rd 2011.
I'm working on JavaScript and stuck in a small issue.
I am receiving this date in JSON response 1322919399447-0500
and I want to format this like: 6:50 PM, Dec 3rd 2011.
I'm not sure if this is the best way (I'm sure it's not, actually), but essentially you can make that datestring into a js Date object, then pull out the pieces to manipulate as you see fit:
var dateThing = new Date(1322919399447-0500);
dateThing.getFullYear(); // 2011
dateThing.getDay(); // 6
dateThing.getDate(); // 3
dateThing.getMonth(); // 11
dateThing.getHours(); // 8 (test for anything over 12, that indicates PM)
dateThing.getMinutes(); // 36
Then you can concatenate those pieces into your own format. Like I said, there's probably a better way, but this works in a pinch.
-0500 in the Date constructor isn't a good idea. For one, it's intended to be a timezone offset (number of hours from UTC). For another, 0500 outside strict mode will result in 320, the decimal value for octal 0500. So actually, you're taking 320 milliseconds away from the actual date value, instead of 5 hours.I used this handy little date format addon and it worked very well for me. Even took care of the pesky internet explorer quirks with the month.
This is a similar date format function I created that uses the same flags that PHP's date function uses.
Here is the snippet with your example input. It is using script linked by Zoidberg.
This code returns formatted UTC date. If you want your local date then remove UTC: from the return statement.
function convertTime(dateString) {
// get ms part from the string
var milis = +dateString.substring(0, 13);
// get timezone part as "# of hours from UTC", e.g. "-0500" -> -5
var offset = +dateString.substring(13, 16);
// move the time for "offset" number of hours (to UTC time)
var date = new Date(milis - offset * 3600000);
// using http://stevenlevithan.com/assets/misc/date.format.js
return date.format("UTC:h:MM TT, mmm dS yyyy");
}
EDIT: Changed + offset * to - offset * as we want to normalize to UTC.