Send JQuery JSON to WCF REST using date Send JQuery JSON to WCF REST using date jquery jquery

Send JQuery JSON to WCF REST using date


I pulled out a lot of hair and shed plenty a tear over this but this worked. I modified the date formatting in your toMSJSON function. WCF accepts this format which I realised thanks to Rick Strahl.

Date.prototype.toMSJSON = function () {    var date = '/Date(' + this.getTime() + ')/'; //CHANGED LINE    return date;};

You also need to convert the dates to UTC time or you get all kinds of funny stuff, so:

  var dt = ...;  var dt1 = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(),   dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));  var wcfDateStr = dt1.toMSJSON();

Hope this helps.


According to: http://msdn.microsoft.com/en-us/library/bb412170.aspx

DateTime Wire Format

DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

When serializing DateTime, Local and Unspecified times are written with an offset, and Utc is written without.

The ASP.NET AJAX client JavaScript code automatically converts such strings into JavaScript DateTime instances. If there are other strings that have a similar form that are not of type DateTime in .NET, they are converted as well.

The conversion only takes place if the "/" characters are escaped (that is, the JSON looks like "\/Date(700000+0500)\/"), and for this reason WCF's JSON encoder (enabled by the WebHttpBinding) always escapes the "/" character.

Your enumerator should be fine.


Here's a mostly seemless solution from This post (modified) which you'd put on the client with JSON.stringify():

jsonData = JSON.stringify([new Date()],     function (k, v) { return this[k] instanceof Date ? '/Date(' + v + ')/' : v; });

Which works in the latest IE, Chrome, and Firefox for me.

Check out JSON.stringify (a native method) and the replacer parameter for hints on converting your enum.