Converting .NET DateTime to JSON [duplicate]

Solution 1:

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]));

Solution 2:

I have been using this method for a while:

using System;

public static class ExtensionMethods {
  // returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
  public static double UnixTicks(this DateTime dt)
  {
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
  }
}

Assuming you are developing against .NET 3.5, it's a straight copy/paste. You can otherwise port it.

You can encapsulate this in a JSON object, or simply write it to the response stream.

On the Javascript/JSON side, you convert this to a date by simply passing the ticks into a new Date object:

jQuery.ajax({
  ...
  success: function(msg) {
    var d = new Date(msg);
  }
}

Solution 3:

To parse the date string using String.replace with backreference:

var milli = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var d = new Date(parseInt(milli));