I have the following code in an ASP.NET MVC3 Controller:
public PartialViewResult GetCalendar(int? month, int? year) { var test = new DateTime((year.HasValue ? year.Value : 1), (month.HasValue ? month.Value : 1), 1); return PartialView("Calendar", new DateTimeOffset(test)); }
My view model is DateTimeOffset?
What is the reason for the exception thrown?
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.
The main difference between it and the simpler DateTime type we all know and love is that it includes a time zone offset from UTC. Thus, it's always clear when looking at a DateTimeOffset what time is meant, whether UTC or local.
The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time.
The DateTimeOffset
constructor first converts any DateTime
that is not of Kind
'UTC' to the equivalent UTC time. It will then check whether the UTC-equivalent DateTime
falls outside of the bounds of DateTimeOffset.MinValue
and DateTimeOffset.MaxValue
, and if it does, will throw an ArgumentOutOfRangeException
similar to the one you are experiencing.
Check the DateTime.Kind
of the variable test
that you are using, and if it is not 'UTC', work out if a conversion to UTC will make the DateTime
specified by test
fall outside of those bounds - according to the MSDN documentation, the MinValue
and MaxValue
(in UTC) are '1/1/0001 12:00:00 AM +00:00' and '12/31/9999 11:59:59 PM +00:00' respectively.
The docs (DateTimeOffset.MinValue) note that:
"Any DateTimeOffset value is converted to Coordinated Universal Time (UTC) before the method performs the comparison with MinValue. This means that a DateTimeOffset value whose date and time are close to the minimum range, but whose offset is positive, may throw an exception. For example, the value 1/1/0001 1:00:00 AM +02:00 is out of range because it is one hour earlier than MinValue when it is converted to UTC."
And also (DateTimeOffset.MaxValue):
"Any DateTimeOffset value is converted to Coordinated Universal Time (UTC) before the method compares it with MaxValue. This means that a DateTimeOffset value whose date and time are close to the maximum range, but whose offset is negative, may throw an exception. For example, the value 12/31/9999 11:00 PM -02:00 is out of range because it is one hour later than MaxValue when it is converted to UTC."
And as per the docs (DateTimeOffset Constructor), the offset that is applied to a non-UTC Kind
is the "offset of the local system's current time zone".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With