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

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.MinValueDateTimeOffset.MaxValue,如果是的话,会抛出一个ArgumentOutOfRangeException类似于您所遇到的一个.

检查您正在使用DateTime.Kind的变量test,如果它不是"UTC",请确定转换为UTC是否会使DateTime指定的值test超出这些范围 - 根据MSDN文档,MinValueMaxValue(以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.

还有(DateTimeOffset.MaxValue):

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

根据docs(DateTimeOffset Constructor),应用于非UTC Kind的偏移量是"本地系统当前时区的偏移量".

  • 像Chamila说的那样,它失败了,因为日期超出了允许的范围.`new DateTimeOffset(DateTime.MinValue)`将在任何时区早于UTC(正偏移)的计算机上失败,并且`new DateTimeOffset(DateTime.MaxValue)`将在任何时区落后于UTC的计算机上失败(负偏移). (8认同)

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 数据类型时,您将不会收到该错误。