Bab*_*mes 20 asp.net-mvc exception datetimeoffset
我在ASP.NET MVC3控制器中有以下代码:
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));
}
Run Code Online (Sandbox Code Playgroud)
我的观点模型是 DateTimeOffset?
抛出异常的原因是什么?
Cha*_*nga 36
该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'.
docs(DateTimeOffset.MinValue)注意到:
"在方法与MinValue进行比较之前,任何DateTimeOffset值都将转换为协调世界时(UTC).这意味着DateTimeOffset值的日期和时间接近最小范围,但其偏移量为正,可能会引发异常.例如,值1/1/0001 1:00:00 AM +02:00超出范围,因为它比MinValue提前一小时转换为UTC.
"在将方法与MaxValue进行比较之前,任何DateTimeOffset值都会转换为协调世界时(UTC).这意味着DateTimeOffset值的日期和时间接近最大范围,但其偏移量为负,可能会引发异常.例如,值12/31/9999 11:00 PM -02:00超出范围,因为当它转换为UTC时,它比MaxValue晚一个小时."
根据docs(DateTimeOffset Constructor),应用于非UTC Kind
的偏移量是"本地系统当前时区的偏移量".
fbi*_*agi 10
我刚刚遇到这个问题,由我的团队介绍,这是一个负面的UTC区域...
chamila_c发布的是发生这种情况的真正原因,但我需要快速修复.
为了"解决它"我基本上创建了这个扩展:
public static class DateTimeExtensions
{
public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime)
{
return dateTime.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime
? DateTimeOffset.MinValue
: new DateTimeOffset(dateTime);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能还想检查MaxValue.
小智 5
如果您正在处理的数据类型是 DateTime,则应该创建一个指定 Kind 的 DateTime 对象。
DateTime maxDate = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.UTC);
Run Code Online (Sandbox Code Playgroud)
当它转换为 DateTimeOffset 数据类型时,您将不会收到该错误。
归档时间: |
|
查看次数: |
17468 次 |
最近记录: |