Victor
Victor

Reputation: 1271

Converting Date in Javascript

My AJAX call returns the datetime value as this

/Date(1320120000000-0400)/

How do I convert it to a readable format (e.g. 11/31/2011) using Javascript?

Upvotes: 0

Views: 912

Answers (3)

paulgendek
paulgendek

Reputation: 1

Calling toDateString will return just the date portion formatted in a human readable form in American English ("Mon Oct 31 2011").

If you specifically need "11/31/2011", then build a custom string using getMonth, getDate, and getFullYear.

var date = new Date(1320120000000-0400);
var formatted = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();

More here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Upvotes: 0

Ibu
Ibu

Reputation: 43810

var date = new Date();
date.setTime("1320120000000");

This should work

You can now format it to a string using, getDay, getMonth,getFullYear methods.

Read More here

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

This is the number of milliseconds since epoch:

new Date(1320120000000) //Tue Nov 01 2011 05:00:00 GMT+0100 (CET)

However, -0400 seems to be a GMT offset which you also have to apply. I guess it has a format of HHMM, so in this case you have to subtract 4:00 hours from given value:

new Date(1320120000000 - 4 * 3600 * 1000)  //Tue Nov 01 2011 01:00:00 GMT+0100 (CET)

Finally note that the Date.toString() method shown in comments uses browser time zone (CET in my case, see: Annoying javascript timezone adjustment issue). You should use getUTC*() methods on Date to get accurate results not affected by browser.

Upvotes: 1

Related Questions