Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting .NET DateTime to JSON [duplicate]

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

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

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

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

If you pass a DateTime from a .Net code to a javascript code, C#:

DateTime net_datetime = DateTime.Now;

javascript treats it as a string, like "/Date(1245398693390)/":

You can convert it as fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

or:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))

If you're having trouble getting to the time information, you can try something like this:

    d.date = d.date.replace('/Date(', '');
    d.date = d.date.replace(')/', '');  
    var expDate = new Date(parseInt(d.date));