Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting json results to a date [duplicate]

Possible Duplicate:
How to format a JSON date?

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!

like image 739
littlechris Avatar asked Aug 07 '09 10:08

littlechris


People also ask

How do you encode a date in JSON?

To represent dates in JavaScript, JSON uses ISO 8601 string format to encode dates as a string. Dates are encoded as ISO 8601 strings and then treated just like a regular string when the JSON is serialized and deserialized.

Can JSON be a date?

JSON Dates are not dates – they are Strings You can represent strings, numbers, Booleans and even objects, arrays and RegEx expressions with language specific literals, but there's no equivalent literal representation for dates.

How do I Stringify a date?

stringify changes time of date because of UTC with JavaScript, we can use JSON. parse to convert the date back to its original format. let currentDate = new Date(); currentDate = JSON. stringify(currentDate); currentDate = new Date(JSON.

Does JSON Stringify convert date to UTC?

JSON Stringify changes time of date because of UTC.


1 Answers

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 
like image 168
Greg Avatar answered Oct 30 '22 15:10

Greg