asp.net-mvc - 应用偏移时表示的 UTC 时间必须介于 0 到 10,000 年之间。参数名称 : offset

标签 asp.net-mvc exception datetimeoffset

我在 ASP.NET MVC3 Controller 中有以下代码:

public PartialViewResult GetCalendar(int? month, int? year)
    {
        var test = new DateTime((year.HasValue ? year.Value : 1), (month.HasValue ? month.Value : 1), 1);
        return PartialView("Calendar", new DateTimeOffset(test));
    }

我的 View 模型是 DateTimeOffset?
抛出异常的原因是什么?

最佳答案

DateTimeOffset构造函数首先转换任何 DateTime不是 Kind 'UTC' 到等效的 UTC 时间。然后它会检查 UTC 是否等效 DateTime超出了 DateTimeOffset.MinValue 的范围和 DateTimeOffset.MaxValue ,如果是,将抛出 ArgumentOutOfRangeException类似于你正在经历的。

检查 DateTime.Kind变量 test您正在使用的,如果它不是“UTC”,请计算转换为 UTC 是否会使 DateTimetest 指定超出这些范围 - 根据 MSDN 文档,MinValueMaxValue (UTC)分别是“1/1/0001 12:00:00 AM +00:00”和“12/31/9999 11:59:59 PM +00:00”。

文档 ( DateTimeOffset.MinValue ) 指出:

“在方法执行与 MinValue 的比较之前,任何 DateTimeOffset 值都会转换为协调世界时 (UTC)。这意味着日期和时间接近最小范围但偏移量为正的 DateTimeOffset 值可能会引发异常。例如,值 1/1/0001 1:00:00 AM +02:00 超出范围,因为它在转换为 UTC 时比 MinValue 早一小时。”

还有( DateTimeOffset.MaxValue ):

“在方法将其与 MaxValue 进行比较之前,任何 DateTimeOffset 值都会转换为协调世界时 (UTC)。这意味着日期和时间接近最大范围但偏移量为负的 DateTimeOffset 值可能会引发异常。对于例如,值 12/31/9999 11:00 PM -02:00 超出范围,因为它在转换为 UTC 时比 MaxValue 晚一小时。”

根据文档( DateTimeOffset Constructor ),应用于非 UTC Kind 的偏移量是“本地系统当前时区的偏移量”。

关于asp.net-mvc - 应用偏移时表示的 UTC 时间必须介于 0 到 10,000 年之间。参数名称 : offset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13799214/

相关文章:

asp.net-mvc - 带有 Redis 的 SignalR 将消息发送到特定的 ConnectionID

c# - 自动化测试中的 DbContext.ChangeTracker 抛出 SQLException

java.lang.IllegalStateException : ViewPager 错误

c# - 调用 .fail(error) 而不抛出异常

c# - 为什么我不能将此字符串解析为 DateTimeOffset 并将系统时钟设置为香港时间?

javascript - 将 DateTimeOffset 持久化到服务器

css - ASP.net MVC 主题更改帮助

c# - ASP.NET MVC $.post 调用返回字符串...需要有关 jqGrid 格式的帮助

java - "Software caused connection abort: socket write error"的官方原因

java - 在 Jersey 消费 OffsetDateTime