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.

3
  • possible duplicate of How to format a JSON date? Commented Dec 3, 2011 at 14:09
  • Is a popular topic, you can find on the existing questions (surely it does) Commented Dec 3, 2011 at 14:09
  • Can you please revisit this question, check the answers and accept the one you like the most? Commented Dec 9, 2011 at 2:15

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, and tons of good stuff in that post ajreal mentioned. Check it out.
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.
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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.