gpt4 book ai didi

datetime - 将 DateTime.MinValue 转换为 DateTimeOffset

转载 作者:行者123 更新时间:2023-12-04 14:50:32 25 4
gpt4 key购买 nike

我正在尝试将 DateTime.MinValue 转换为 DateTimeOffset 值,但出现 ArgumentOutOfRange 异常。

我在看 the MSDN article on implicit conversions of DateTime to DateTimeOffset并且异常部分指出我将在以下情况下收到此 ArgumentOutOfRange 异常;

... The Coordinated Universal Time (UTC) date and time that results from applying the offset is earlier than MinValue. ...



为什么下面的代码会抛出异常;
DateTime test = DateTime.MinValue;
DateTimeOffset dto = test;

仅仅是因为我的时区吗?我在 GMT +8,但我对上述代码的理解是测试是用 Unspecified 类型创建的。

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

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

最佳答案

如果您在 GMT+8,则本地时间为 DateTime.MinValue对应于早于 DateTime.MinValue 的 UTC 时间,因此异常(exception)。从您引用的文档中:

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.



所以逻辑上你会有一个 DateTimeMinValueOffset 8 小时,但这意味着应用偏移量产生的 UTC 日期/时间早于可以表示的时间。

(不要忘记向 UTC 添加偏移量以获得本地时间,或从本地时间减去它以获得 UTC。在 Noda Time 中,我们通过为 OffsetLocalInstant 中的每一个使用类型来强制执行此操作。和 Instant ,并且只允许您执行相应的操作...)

关于datetime - 将 DateTime.MinValue 转换为 DateTimeOffset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6924198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com