2016-03-07

.NET to JSON - Date Nightmare

Handling dates correctly is a nightmare.
It seems that every product implements its own Date type. Today I encountered yet another date issue while I was serializing .NET object to JSON to pass it to my View. It might seems easy to do this, as there is JavaScriptSerializer available which takes object and returns JSON string of the object:
ViewBag.AssignedLicences = new JavaScriptSerializer().Serialize(assignedLicences.ToList());
While JSON format is text based, lightweight and simple it doesn't offer many data types. The data types supported in JSON include string, number, boolean, array, object and null. Lack of support for complex types poses some difficulties while dealing with dates. Since there is no special representation for dates in JSON, ASP.NET uses its own way to deal with dates.
-- Developer.com

Let’s assume my object assignedLicences was something like this:
var assignedLicences = new AssignedLicences() {
   OrderDate = DateTime.Now,
   LicenceCode = "ABCD" }
When this object is serialized, JSON content for OrderDate is something like: “/Date(83641860000000”). Not really a nice representation of a date!
If you have time you can check the meaning of the numbers and let me know if you find out. While you do seraching I give you nice JavaScript formating solution:
function GetJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
And remember: Never trust a date Winking smile

No comments:

Post a Comment