Convert serialzed JSON date string to a Javascript Date() object

When an DateTime object in C# is converted into a JSON serialized object for a web page, the format of the string looks like this in the JSON object:

/Date()/

See this for more details on why this format was chosen. This is all well and good, but how do you use that? A similar question and answer can be found here, but the solution posted there misses the possibility of a negative int.

To expand just a bit on the solution posted there, we'll account for negative numbers:


var someDate = new Date(+jsonDate.replace(/\/Date\((-?\d+)\)\//gi, "$1"));

The three key things to note here are:

1. This method does not use eval(). eval can be a very dangerous thing to use since it will execute any javascript, so generally we try to avoid using it altogether. This is why we use JSON.parse, for example, instead of eval.

2. The "+" operator is a type converter in javascript that converts the string to an int.

3. The "-?" because the date value can, indeed, be a negative value (try 03/29/1938 for example).

Comments

  1. Serialized dates are a pain to work with. Your solution worked for me. Now I just need to format the date to a short date for a date selector. Thanks!

    ReplyDelete

Post a Comment

Popular posts from this blog

35x Improved T-SQL LevenShtein Distance Algorithm...at a cost

The hidden workings of __doPostBack - Full or Partial Postback?

Facing Death...dum de dum dum