Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API Date format in JSON does not serialise successfully

All,

We are using ASP.NET Web API where we have a REST based service with JSON for the payload. If I pass the following Date as a string e.g

sampleObj: {
...
myDate: "31/12/2011 00:00:00",
...
}

as an attribute value in the JSON payload, the date attribute gets deserialised into a DateTime.MinValue. Is the string format valid?

We know the format "2012-10-17 07:45:00" serialises successfully but we cannot guarantee that all dates received will be in this format. What are the valid options?

like image 885
bstack Avatar asked Oct 17 '12 14:10

bstack


People also ask

Does JSON support date format?

JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.

How do I set date format in JSON?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.


2 Answers

In ASP.NET Web API, you can add different Json.NET DateTimeConverters through the JsonFormatter's SerializerSettings to make your service understand different DateTime format.

However, I do not think there is a default DateTimeConverter from Json.NET that takes in this format "31/12/2011 00:00:00". In this case you implement your custom DateTimeConverter.

WebApiConfig.cs:

        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
             new IsoDateTimeConverter());
        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
             new MyDateTimeConverter());

Custom DateTimeConverter:

public class MyDateTimeConverter : DateTimeConverterBase
{
    //...
}  

For more information about how to write a custom DateTimeConverter, I found something on stackoverflow that you might find useful: How to create a json.net Date to String custom Converter.

like image 76
Maggie Ying Avatar answered Oct 16 '22 04:10

Maggie Ying


Just set globalization in web.config:

<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB"/>

and then, in Global.asax.cs > Application_Start, set JsonFormatter to use the current culture:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Culture = System.Globalization.CultureInfo.CurrentCulture;
like image 34
claudiu.nicola Avatar answered Oct 16 '22 06:10

claudiu.nicola