DateTime差异计算出现OverflowException

本文关键字:OverflowException 计算 DateTime | 更新日期: 2023-09-27 18:24:59

我在这个小片段上得到了一个奇怪的错误:

private int CalculateDifference(DateTime date1, DateTime date2)
{
    var difference = date1 - date2;
    return Math.Abs((int)difference.TotalSeconds);
}

在我的情况下,我计算的差值为3520789176.4909997秒。该程序抛出了一个我在C#编码十年中从未见过的异常:

System.OverflowException: "Negating the minimum value of a twos complement number is invalid."

我很确定这与浮点算法有关,但我不了解细节,我只需要一个足够的解决方案来确定两个日期值的差异。

DateTime差异计算出现OverflowException

问题在于,当a double超出了可以在int中表示的值的范围时—是-2147483648到2147483647,根据C#规范,结果是未定义的(请参阅下面的Jeppe Stig Nielsen的评论),但在.NET实现中,结果是int.MinValue。因此,当您将difference转换为int时,它会取值-2147483648,然后无法使用Math.Abs 求反

如果您将此方法转换为使用long,它应该可以工作:

private long CalculateDifference(DateTime date1, DateTime date2)
{
    var difference = date1 - date2;
    return Math.Abs((long)difference.TotalSeconds);
}

您也可以通过在获得绝对值后简单地转换为int来解决此问题:

private int CalculateDifference(DateTime date1, DateTime date2)
{
    var difference = date1 - date2;
    return (int)Math.Abs(difference.TotalSeconds);
}

根据msdn:Int的值。最大值为2147483647

你的数字似乎比这个还要多。

相关文章:
  • 没有找到相关文章