1

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.

Rob W
  • 341,306
  • 83
  • 791
  • 678
BASEER HAIDER JAFRI
  • 939
  • 1
  • 17
  • 35
  • possible duplicate of [How to format a JSON date?](http://stackoverflow.com/questions/206384/how-to-format-a-json-date) – ajreal Dec 03 '11 at 14:09
  • Is a popular topic, you can find on the existing questions (surely it does) – ajreal Dec 03 '11 at 14:09
  • Can you please revisit this question, check the answers and accept the one you like the most? – kubetz Dec 09 '11 at 02:15

4 Answers4

1

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.

Zoidberg
  • 10,137
  • 2
  • 31
  • 53
1

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.

Justin Lucente
  • 1,151
  • 1
  • 8
  • 9
  • Oh, and tons of good stuff in that post ajreal mentioned. Check it out. – Justin Lucente Dec 03 '11 at 14:43
  • 2
    The `-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. – Andy E Dec 03 '11 at 15:38
1

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.

kubetz
  • 8,485
  • 1
  • 22
  • 27
1

This is a similar date format function I created that uses the same flags that PHP's date function uses.

PHP date function in Javascript

anson
  • 4,156
  • 2
  • 22
  • 30