Tuesday, February 2, 2016

How to Keep DateTime Unchanged when JSON is Parsed through Web API

You might have experienced this where when you send a DateTime object to Web API with the Time Offset, Web API is doing the math and calculating the UTC DateTime using the Offset itself.

If I give an example, this is how my client side code sends the DateTime object to Web API.

image
DateTime in Client Side
And from the Web API, this is what I am getting.
image
DateTime in Server Side
So as you can see here, the Web API’s JSON formatter has converted the passed DateTime to UTC time using the given Offset.

Sometimes this is not the expectation and we want to pass the DateTime as it is. Now let’s see how we can achieve it by simple changing the Web API JSON formatter settings.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            DateTimeZoneHandling = DateTimeZoneHandling.Local
        };
 
        // other api configuration
    }
}
Now if I send the data back again, I am getting the DateTime as it it without converting it to UTC time.
image
DateTime in Server Side
Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment