开发者

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 er开发者_运维知识库ror.


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...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜