Serializing .NET types that contain DateTime

I recently had to de-serialize a JSON string that contained a date. The object contained valid DateTime properties and was then serialised. When it was subsequently passed to the receiving application, the serialised object could not be de-serialised as the dates were not in a valid format.

Example of the problem.

Hide Copy Code

//the client application serialises the date
string jsonDate = JavaScriptSerializer().Serialize(DateTime.Now);
//the receiving application attempts to de-serialise the date
DateTime dt = new JavaScriptSerializer().Deserialize<DateTime>(jsonDate); //this throws an exception!

When viewing the JSON representation of the date it would appear as follows.

Hide Copy Code

/Date(1484904895490)/

The fix I eventually managed to figure out that solved the problem was to use the JsonConvert.SerializeObject() function instead.

Hide Copy Code

var isoConvert = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
DateTime dt = JsonConvert.SerializeObject(jsonDate, isoConvert);

This solution works with any object that contains dates (or even those that don’t include dates). I now use this code in my serialization function throughout my application.

A father, cyclist, vegetarian, atheist, geek and multiple award winning technical author. Loves real ale, fine wine and good music. All round decent chap.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store