0

I am having issues in my local environment (ASP.NET MVC - UTC-5 Offset) where MVC Model Binding is converting my UTC DateTimes back to the Local DateTime.

In the DB we are attempting to store all datetimes in UTC. EF Reads these dates fine out of the DB correctly as UTC, and on the client i am succesffuly converting these back to local time on display, and sending UTC back to the server on posts. Here is an example post:enter image description here

However on entry into the controller, the datetime is now in local time: enter image description here

My JsonSerializer in global.asax looks like this:

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

I assumed the Json serialiser would convert that to UTC on model binding back in to the controller, but its not. Other than manually converting every date on back to UTC, is there any way to get this working site wide so that it reads the JSON dates from clients as UTC?

dalcam
  • 889
  • 9
  • 22
  • Hi @Json - the only time i modify the dates is on JSON Serialization to tell the receiver that the date IS UTC: `JsonConvert.DefaultSettings = () => new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc };` – dalcam Aug 15 '18 at 23:39
  • Thats the thing Json - im not touching the dates in the controller or the repository. Im simply using Automapper to map from the VM to the DTO and then inserting. I will add this if you really think this is neccessary but i cant yet see how it is! – dalcam Aug 15 '18 at 23:54
  • 1
    My best guess here is that you need to config your ("Automapper") mapping for dates. try creating a new map specifying the kind of conversion that you want – JSON Aug 16 '18 at 00:02
  • 1
    @mjwills you are completely right! I was looking at the date component thinking that the 12am was the UTC time! Well this is embarrasing... – dalcam Aug 16 '18 at 00:42
  • Thanks @mjwills i have done, and now the question has changed completey! Its coming into the model binder as a local date now that I know not to look at the time in the date component! Thanks so much for your help and advice. Much appreciated. – dalcam Aug 16 '18 at 01:53
  • 1
    https://stackoverflow.com/questions/10293440/how-to-make-asp-net-mvc-model-binder-treat-incoming-date-as-utc may be of interest. – mjwills Aug 16 '18 at 01:56
  • thanks @mjwills that was exactly what i needed. Thank you so much! – dalcam Aug 16 '18 at 02:49

1 Answers1

0

As per @mjwills coment, this article answers and fixes the problem: How to make ASP.Net MVC model binder treat incoming date as UTC?

dalcam
  • 889
  • 9
  • 22