Search code examples
sql-serverjsonasp.net-web-apiodataodata-v4

Serializing dates to JSON seems to alter the date one hour back


I'm trying to understand why dates stored in my MSSQL server are being altered back one hour when I view them in JSON format.

Here is the Datetime date stored in MSSQL

2015-08-12 00:00:00.000

Here is debug mode in Visual Studio showing that the date "appears" to be retrieved correctly from the database.

{8/12/2015 12:00:00 AM}

And here is the JSON output - the date is one hour earlier! I see that the json timezone is -6, and the database timezone doesn't appear to have that, but I don't have any special settings in my web api config. I'm really not understanding what is going on here. Appreciate any help.

"2015-08-11T23:00:00-06:00",

Edit: My pictures didn't show up so I edited to show the dates in text format - hope that is allright.


Solution

  • When moving to OData V4 (from earlier versions) one of the first 'hickups' we run into is that V4 does not support 'DateTime' but 'DateTimeOffset'. In .Net terms we're moving from a "Date assumed to be in locale timezone of the server running it" to "DateTimeOffset" which explicitly included the timezone information itself.

    OWin will emit the DateTimeOffset based on your thread's culture info. Your solution will then lie in making sure when converting between "DateTime" and "DateTimeOffset" (DB/EF and OWin respectively) that you don't rely on your local thread's locale setting, but force it to be considered UTC.