posted 8/10/2011 by Hajan Selmani
Yesterday I posted a blog about Serializing specific class properties to JSON string using JavaScriptSerializer class and LINQ. In the examle I have shown the serialization of string, integer and boolean properties. One of the readers asked about serializing DateTime to JSON.
To read how to perform the serialization, first read the blog post here.
We have the following JSON Array of objects with DateTime values:
[ { "BirthDate": "\/Date(499993200000)\/" }, { "BirthDate": "\/Date(359848800000)\/" }, { "BirthDate": "\/Date(227487600000)\/"}];
<script type="text/javascript"> var jsonString = [ { "BirthDate": "\/Date(499993200000)\/" }, { "BirthDate": "\/Date(359848800000)\/" }, { "BirthDate": "\/Date(227487600000)\/"}]; for (i in jsonString) { //get the jsonDate from the JSON string object BirthDate property var jsonDate = jsonString[i]["BirthDate"]; //alert the jsonDate value alert(jsonDate); //check //using regex we remove the \/Date(...) from each item var currentDate = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)")); //alert the result value alert(currentDate); //check } </script>
We do itteration over each object inside the jsonString array. After that we get the BirthDate property value and using the regular expression we replace the \/Date(date-value)\/ with new Date(date-value). Practically, we get only the integer number and put it inside new Date(number-here).
Run the example and you will see that the values should be equal to the following C# DateTime objects:
- BirthDate = new DateTime(1985, 11, 05)
- BirthDate = new DateTime(1981, 05, 28)
- BirthDate = new DateTime(1977, 03, 18)
Hope this was helpful.
Regards,Hajan
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18