It is agreed by the .Net community that DateTime should not be used when we develop .Net applications. You can read more about why that here. In short the least we can do is to use DateTimeOffset
instead. But this post is not about the common problems associated with using DateTime. But rather it’s about how Asp.Net Core/MVC Model binding behave when we try to bind a JavaScript ISO date format to DateTime. I’m going to show what happens when we try to do that and the problems that can arise from this. Then we’ll see a rather easy fix.
Asp.Net MVC/Core Iso Date Model Binding Behavior
As can be seen from the image below, we are sending a UTC value to our controllers. Then the value will be bound to DateTime type. But for ISO date format, the app is going to automatically convert the time to local time. First I’ve sent a ISO date value and tried to bind ISO Date Format to DateTime. You can see it is converted to local, next I tried to send a UTC value to be bound to a DateTimeOffset, you can see this time the time is bound correctly.
Why Model Binding do that and the Easy Fix
I think the reason it happens is that DateTime object does not have any concept of UTC and offset. So if we send a UTC value with an offset to DateTime object the value will be lost. Unless the MVC model binder takes that value and use the offset to convert the value to local time. But the problem is this is not what we want necessarily. The only real solution to fix these types of problems is to disallow DateTime completely. But if an application is already written relying on DateTime, then it’s beneficial to be aware of this type of behaviors.
Summary
In this post we saw what can happen when we try to bind ISO Date Format to DateTime in Asp.Net Core/MVC. I also explained why that happens and how to fix it.