Skip to content Skip to sidebar Skip to footer

Jquery.param() - Doesn't Serialize Javascript Date Objects?

jQuery.param({foo: 1}); // => 'foo=1' - SUCCESS! jQuery.param({bar: new Date()}); // => '' - OUCH! There is no problem with encodeURIComponent(new Date()), wh

Solution 1:

You're probably going to want the date transformed into a string, since that's what it's going to have to be on the wire anyway.

$.param({bar: newDate().toString()});

Now you may want it formatted in some particular way so that your server gets something it can parse. I think that the datejs library has support for formatting, or you could roll your own by picking out pieces of the date with getDate(), getMonth(), getYear() etc.

Solution 2:

If you work with Microsoft products on the server side you should take in consideration, that Microsoft serialize Date as a number of milliseconds since UTC, so as a number. To be more exact, the serialization string look like /Date(utcDate)/, where utcDate date is this number. Because JSON supports the backslash as an escape character you should use code like following to serialize a Date object myDate:

"\/Date(" +  Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(),
                      myDate.getUTCDate(), myDate.getUTCHours(),
                      myDate.getUTCMinutes(), myDate.getUTCSeconds(),
                      myDate.getUTCMilliseconds()) + ")\/"

Solution 3:

I think this is a jQuery bug in the following context:

  • jQuery 1.4.2 (1.3.2 works)
  • new methods added into Date.prototype

Post a Comment for "Jquery.param() - Doesn't Serialize Javascript Date Objects?"