views:

198

answers:

2

I have the following result from a $getJSON call from JavaScript. How do I convert the start property to a proper date in JavaScript?

[ {"id":1,"start":"\/Date(1238540400000)\/"}, {"id":2,"start":"\/Date(1238626800000)\/"} ]

Thanks!

+1  A: 

If that number represents milliseconds, use the Date's constructor :

var myDate = new Date(1238540400000);
Andreas Grech
+1  A: 

You need to extract the number from the string, and pass it into the Date constructor:

var x = [ {"id":1,"start":"\/Date(1238540400000)\/"}, {"id":2,"start":"\/Date(1238626800000)\/"} ];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1));

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
Greg
Don't * 1 to convert a string to a number. Use parseInt(number, 10). Also, if you want a cool trick like * 1, just try +str to make it a number.
Eli Grey