32

我在 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));
    }

我的视图模型是DateTimeOffset?

抛出异常的原因是什么?

4

4 回答 4

55

构造DateTimeOffset函数首先将任何DateTime不属于Kind“UTC”的时间转换为等效的 UTC 时间。然后它将检查 UTC 等效值是否超出andDateTime的范围,如果超出,将抛出与您正在经历的相似的情况。DateTimeOffset.MinValueDateTimeOffset.MaxValueArgumentOutOfRangeException

检查您正在使用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”。

文档(DateTimeOffset.MinValue)注意到:

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

还有(DateTimeOffset.MaxValue):

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

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

于 2012-12-10T10:49:55.840 回答
17

我刚刚遇到了这个问题,由我的团队中位于负 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);
    }
}

您可能还想检查 MaxValue。

于 2014-07-22T15:13:33.037 回答
4

如果您处理的数据类型是 DateTime,您应该创建一个 DateTime 对象来指定 Kind。

DateTime maxDate = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.UTC);

当它转换为 DateTimeOffset 数据类型时,您将不会收到该错误。

于 2020-10-23T15:47:29.363 回答
1

这可能会在 Azure Function 开发期间发生,当您在 function.json 中设置计时器触发器计划使其永远不会运行时,如下所示:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
        "name": "mytimer",
        "type": "timerTrigger",
        "direction": "in",
        "schedule": "0 0 0 31 2 *"
    }
  ]
}

...我已将其设置为在 2 月 31 日运行(即从不。)显然“从不”超出了允许的日期范围。解决方案是不那么棘手,只需在遥远的未来设定一个真实的日期:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
        "name": "mytimer",
        "type": "timerTrigger",
        "direction": "in",
        "schedule": "0 0 0 1 1 * "
    }
  ]
}

(1月1日运行一次,明年才运行。)

再次感谢 Chamila Chulatunga 对问题根源的描述。

于 2021-05-02T18:25:50.023 回答