Passing UTC DateTime to Web API HttpGet Method results in local time Passing UTC DateTime to Web API HttpGet Method results in local time json json

Passing UTC DateTime to Web API HttpGet Method results in local time


The query string parameter value you are sending 2014-04-01T00:00:00Z is UTC time. So, the same gets translated to a time based on your local clock and if you call ToUniversalTime(), it gets converted back to UTC.

So, what exactly is the question? If the question is why is this happening if sent in as query string but not when posted in request body, the answer to that question is that ASP.NET Web API binds the URI path, query string, etc using model binding and the body using parameter binding. For latter, it uses a media formatter. If you send JSON, the JSON media formatter is used and it is based on JSON.NET.

Since you have specified DateTimeZoneHandling.Utc, it uses that setting and you get the date time kind you want. BTW, if you change this setting to DateTimeZoneHandling.Local, then you will see the same behavior as model binding.


If you want the conversion to be transparent, then you could use a custom TypeConverter:

public sealed class UtcDateTimeConverter : DateTimeConverter{    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)    {        return ((DateTime)base.ConvertFrom(context, culture, value)).ToUniversalTime();    }}

and wire it up using:

TypeDescriptor.AddAttributes(typeof(DateTime), new TypeConverterAttribute(typeof(UtcDateTimeConverter)));

Then the query string parameter will be instantiated as DateTimeKind.Utc.


I ended up just using the ToUniversalTime() method as parameters come in.