2

My issue is similar to this: Asp.net WebApi deserializes UTC time string to local time

Except I am using ([FromBody] dtoWithTime) in my controller method

The controller call looks like

public JsonResult DiscoverProject([FromBody] dtoWithTime dto)    {}

where (I have simplified this for example use.)

[Serializable]
public class dtoWithTime
{
  public DateTime? dateName { get; set; }
}

The request is coming in as a POST with these headers/data (taken from fiddler)

accept: application/json
content-type: application/json
content-length: 281
Connection: keep-alive
{"dateName":"2014-05-31T00:00:00.000Z"}

When the date gets into the controller it becomes 2014-05-30 20:00:00

I want the date to come in as sent from the UI with the Utc kind. I am able to manipulate the date with ToUniversalTime() in the controller and this works as I want with the exception that the SpecFlow tests that check this date fail. If I could get the serializer to keep the Utc time all would be good.

What I have tried is to use is the JsonDotNetValueProviderFactory and setting the default settings in the global.asax.cs

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

This worked for me but broke many of the serializations in our app including enums.

So is there anyway to decorate the DateTime? or set a default date type for the MVC json deserializer?

Community
  • 1
  • 1
Maggie
  • 1,546
  • 16
  • 27

1 Answers1

0

JSON is a fantastic format for transmitting data. Unfortunately, the one thing that it does not do well is Dates. There exist many workarounds for getting them to work properly on different platforms. Ultimately what we ended up doing is sending all of our JSON Date data as strings. Then in our controllers we converted them to a real DateTime type using TryParse:

DateTime myDate
if (DateTime.TryParse(inputJsonStringDate, out myDate))
    //Success
else
    //Not a valid date
  • I am trying to avoid adding code to the controllers so we do not have to be aware when a DateTime is added to a dto. We have other apps where we pass strings for dates. – Maggie May 28 '14 at 22:08