4

Possible Duplicate:
How to format a JSON date?

I am calling a JSON web service via Javascript, and the StartDate field is /Date(1268524800000)/. How do I convert this to a human readable format?d

Community
  • 1
  • 1
TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • What format is it in? Is it a time stamp? If the web service has documentation, it should be in there – Pekka Nov 24 '11 at 18:15
  • 5
    Same as this [question](http://stackoverflow.com/questions/206384/how-to-format-a-json-date) – Nathan Nov 24 '11 at 18:16
  • 1
    Well, this format is arguably not immediately recognizable. I think this many downvotes are a little harsh. (But +1 @Nathan for finding a great dupe) – Pekka Nov 24 '11 at 18:16
  • the web service help says the type is "type="xs:dateTime"" – TruMan1 Nov 24 '11 at 18:30
  • It appears to be milliseconds since 1970-01-01 00:00:00 UTC; the date represented is Sun 2010-03-14 00:00:00 UTC. (This doesn't answer the question of how to convert it, but it provides a clue of how to do it if you're using some language other than JavaScript.) Of course, one way to convert it to human-readable format is to train yourself to read that format. 8-)} – Keith Thompson Nov 24 '11 at 18:44

3 Answers3

11

Try this:

var str = "/Date(1268524800000)/";
var num = parseInt(str.replace(/[^0-9]/g, ""));
var date = new Date(num);
alert(date);

Fiddle: http://jsfiddle.net/dS2hd/

Niels
  • 48,601
  • 4
  • 62
  • 81
1

You can use a regex to get the milliseconds, then use the Date constructor to get a Date object. Once you have your date object, you can do whatever you want with it.

var ms = parseInt("/Date(1268524800000)/".match(/\((\d+)\)/)[1]);
var d = new Date(ms);
alert(d.toString());
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0

You can either eval() it, or you can extract the number and pass it to a Date constructor.

if (/^\/Date\((-?\d+)\)\/$/.test(val)) {
    var serial = parseInt(RegExp.$1);
    val = new Date(serial);
}

I've seen dates expressed as /Date(1234567890000-0500)/, so a more robust procedure may be called for to handle the UTC offset.

gilly3
  • 87,962
  • 25
  • 144
  • 176