How to make ASP.Net MVC model binder treat incoming date as UTC?

C.J. picture C.J. · Apr 24, 2012 · Viewed 13.2k times · Source

I'm posting an object to an MVC controller. The object contains a field called StartDt and on the client it is a javascript Date object in local time.

When I call JSON.stringify on the object and POST it to the server using jQuery's ajax method I can see in Firebug that what's being sent to the server is an ISO string like "1900-12-31T13:00:00.000Z" which I believe should be the local time in UTC format.

When I look at the DateTime field in my controller though, it looks like its back to local time and not UTC. How can I fix this?

I want to store the UTC version of the Date that came from the client.

Answer

David Boike picture David Boike · Nov 12, 2012

I found a gist on Google with code for an ISO 8601 compliant DateTime Model Binder, and then modified it like this:

public class DateTimeBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var name = bindingContext.ModelName;
        var value = bindingContext.ValueProvider.GetValue(name);
        if (value == null) 
            return null;

        DateTime date;
        if (DateTime.TryParse(value.AttemptedValue, null, DateTimeStyles.RoundtripKind, out date))
            return date;
        else
            return base.BindModel(controllerContext, bindingContext);
    }
}

I believe the gist code is too restrictive - it wants 6 decimal places on seconds or it will not accept the timestamp. This uses TryParse instead of TryParseExact, so it will technically accept a LOT of timestamp types. The important part is that it uses the DateTimeStyles.RoundtripKind to respect the time zone implied by the Z. So this is no longer technically an ISO 8601 specific implementation.

You could then hook this into the MVC pipeline with a model binder attribute or with this snippet in an App_Start:

var dateTimeBinder = new DateTimeBinder();

ModelBinders.Binders.Add(typeof(DateTime), dateTimeBinder);
ModelBinders.Binders.Add(typeof(DateTime?), dateTimeBinder);