Converting .NET DateTime to JSON

user76071 picture user76071 · Jun 19, 2009 · Viewed 204.5k times · Source

Possible Duplicate:
How to format a JSON date?

My webs service is returning a DateTime to a jQuery call. The service returns the data in this format:

/Date(1245398693390)/

How can I convert this into a JavaScript-friendly date?

Answer

vahidg picture vahidg · Jun 19, 2009

What is returned is milliseconds since epoch. You could do:

var d = new Date();
d.setTime(1245398693390);
document.write(d);

On how to format the date exactly as you want, see full Date reference at http://www.w3schools.com/jsref/jsref_obj_date.asp

You could strip the non-digits by either parsing the integer (as suggested here):

var date = new Date(parseInt(jsonDate.substr(6)));

Or applying the following regular expression (from Tominator in the comments):

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/; 
var m = re.exec(jsonDate); 
var d = new Date(parseInt(m[0]));