Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DateTime.MinValue to DateTimeOffset

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.

like image 656
Mr Moose Avatar asked Aug 03 '11 09:08

Mr Moose


1 Answers

If you're in GMT+8, then a local time of DateTime.MinValue corresponds to a UTC time earlier than DateTime.MinValue, hence the exception. From the documentation you referenced:

If the value of the DateTime.Kind property is DateTimeKind.Local or DateTimeKind.Unspecified, the date and time of the DateTimeOffset object is set equal to dateTime, and its Offset property is set equal to the offset of the local system's current time zone.

So logically you would have a DateTime of MinValue with an Offset of 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, LocalInstant and Instant, and only allow you to perform the appropriate operation...)

like image 89
Jon Skeet Avatar answered Nov 10 '22 01:11

Jon Skeet