将DateTime.MinValue转换为DateTimeOffset [英] Converting DateTime.MinValue to DateTimeOffset

查看:236
本文介绍了将DateTime.MinValue转换为DateTimeOffset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将DateTime.MinValue转换为DateTimeOffset值,但是我得到一个ArgumentOutOfRange异常。

I am trying to convert DateTime.MinValue to a DateTimeOffset value but am getting an ArgumentOutOfRange exception.

我正在查看关于DateTime到DateTimeOffset的隐式转换的MSDN文章,异常部分指出,当

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;


...
由于应用偏移量而导致的协调世界时(UTC)日期和时间比MinValue早
...

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

只是因为我的时区?我在GMT +8,但是我对上述代码的理解是测试是用非特定的类创建的。

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.

我正在通过简单地测试我的DateTime的MinValue来解决这个问题,如果是,则使用DateTimeOffset.MinValue。

I am working around the issue by simply testing for MinValue of my DateTime, and if so, then using DateTimeOffset.MinValue instead.

我只是好奇为什么我的未指定的DateTime对象导致错误。

I am merely curious as to why my unspecified kind DateTime object causes the error.

推荐答案

如果您使用的是GMT + 8,则 local 时间 DateTime.MinValue 对应于UTC 时间早于 DateTime.MinValue ,因此是异常。从您引用的文档中:

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:


如果DateTime.Kind属性的值为DateTimeKind.Local或DateTimeKind.Unspecified,则日期和时间的DateTimeOffset对象设置为等于dateTime,其Offset属性设置为等于本地系统当前时区的偏移量。

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.

所以在逻辑上你将具有 DateTime MinValue 偏移量为8小时,但这意味着应用偏移量的UTC日期/时间早于可以表示。

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.

不要忘记,您将添加到UTC的偏移量以获取本地时间,或者从当地时间减去以获取UTC。在 Noda Time ,我们通过使用 Offset LocalInstant Instant ,只允许您执行适当的操作ation ...)

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

这篇关于将DateTime.MinValue转换为DateTimeOffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆