Converting DateTime.MinValue to DateTimeOffset

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 05:13:45

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/6924198/converting-datetime-minvalue-to-datetimeoffset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!