我在 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 是否会使 DateTime
由 test
指定超出这些范围 - 根据 MSDN 文档,MinValue
和 MaxValue
(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/