ASP.Net Web API: Controlling date formats with JSON.Net

Monday, January 19, 2015
by Sean McAlinden

API's that return non-standard dates are a real pain, I recently had to interact with an API which was returning a date serialized with the proprietary Microsoft DateTime format - apart from being ugly, it is also useless when clients from differing platforms need to use the API.

We have no excuse for returning non-standard dates anymore as libraries like JSON.Net make it so easy to control.

The following code utilises JSON.Net:

var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

And there you have it, just stick that bit of code in your WebApiConfig class or Global.asax and you're done.

You will now be returning well formatted ISO 8601 dates such as 2015-01-19T23:08:57.3010754Z

Happy coding.