JavaScript, JSON, WCF, and passing dates, oh my!!!!

I spent more time than I will EVER admit trying to figure out what the heck was wrong with my code, passing a date created by the jQuery UI datepicker into my .NET WCF service. I tried tick conversions (which would wind up sending a date WCF didn’t understand). The only things I COULD get WCF to understand, read around the year 1970. So, with a bit of research, I wound up with the following code to convert a JavaScript date to a format that WCF wants to see.

$.ajax({
     type: "POST",
     contentType: "application/json; charset=utf-8",
     url: "/WebServices/WebServiceHost.svc/scorePhotographer",
     data: '{"datevisited": "\\\/Date(' + Date.UTC(x.getUTCFullYear(), x.getUTCMonth(), x.getUTCDate(), x.getUTCHours(), x.getUTCMinutes(), x.getUTCSeconds(), x.getUTCMilliseconds()) +
          (-x.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(x.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(x.getTimezoneOffset() / 60)) + '00' +
          ')\\\/" +
          '"}',
     dataType: "json",
     dataFilter: function(data, type) {
     var d = data.replace(/"\\\/(Date\(.*?\))\\\/"/gi, 'new $1');
     return d;
},
success: function (msg) {
     // blah
},
error: function (e) {
     //blah
}
});

Leave a Reply

Your email address will not be published. Required fields are marked *