BASEER HAIDER JAFRI
BASEER HAIDER JAFRI

Reputation: 949

How to format date in correct format in JavaScript

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.

Upvotes: 1

Views: 402

Answers (4)

kubetz
kubetz

Reputation: 8556

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.

Upvotes: 1

anson
anson

Reputation: 4164

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

Upvotes: 1

Justin Lucente
Justin Lucente

Reputation: 1161

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.

Upvotes: 1

Zoidberg
Zoidberg

Reputation: 10323

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.

Upvotes: 1

Related Questions