I am trying to convert DateTime.MinValue to a DateTimeOffset value but am getting an ArgumentOutOfRange exception.
I was looking at the the MSDN article on implicit conversions of DateTime to DateTimeOffset and the Exception section states that I’ll receive this ArgumentOutOfRange exception when;
…
The Coordinated Universal Time (UTC) date and time that results from applying the offset is earlier than MinValue.
…
Why then does the following code throw the exception;
DateTime test = DateTime.MinValue;
DateTimeOffset dto = test;
Is it simply due to my timezone? I am in GMT +8, but my understanding of the above code is that test is created with an Unspecified kind.
I am working around the issue by simply testing for MinValue of my DateTime, and if so, then using DateTimeOffset.MinValue instead.
I am merely curious as to why my unspecified kind DateTime object causes the error.
If you’re in GMT+8, then a local time of
DateTime.MinValuecorresponds to a UTC time earlier thanDateTime.MinValue, hence the exception. From the documentation you referenced:So logically you would have a
DateTimeofMinValuewith anOffsetof 8 hours, but that means that the UTC date/time resulting from applying the offset is earlier than can be represented.(Don’t forget that you add an offset to UTC to get a local time, or subtract it from a local time to get UTC. In Noda Time we enforce this by using a types for each of
Offset,LocalInstantandInstant, and only allow you to perform the appropriate operation…)