Monday, February 28, 2011

DateTime, .net JavaScriptSerializer, JSON and Javascript

If you're using JavaScriptSerializer and are having trouble handling the way it serialized DateTime types to JSON then read on, this might help.

Scenario

On a page I have:
  • an html textbox element set as a JQuery datepicker
  • a button that makes an AJAX call and returns a date and populates the above control
  • The method I call on that ajax request is using the .net JavaScriptSerializer that serializes dates the following way:
    /Date(628318530718)/
    
  • Im using the following to populate the textbox:
    $('#txtDate').datepicker('setDate', item.Date);
    

Problem

On IE the textbox displays the the following: NaN/NaN/NaN
Somehow FF is able to unwrap this and show the correct value on the textbox.
Nice! :(

Solution

We must unwrap that value our-selfs like shown bellow:
myDate =  new Date(parseFloat(item.Date.slice(6, 19)));
$('#txtDate').datepicker('setDate', myDate);

0 comentários: