DateTime差异计算的OverflowException

时间:2013-07-26 11:50:20

标签: c# .net datetime floating-point

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

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."

我很确定它与浮点算术相关,但我不了解细节,我只需要一个足够的解决方案来确定两个日期值的差异。 / p>

2 个答案:

答案 0 :(得分:6)

问题是,当一个双精度超出int中可以表示的值的范围时 - -2,147,483,6482,147,483,647,结果是根据C#规范(参见下面的Jeppe Stig Nielsen's comment),但在.NET实现中,是int.MinValue。因此,当您将difference转换为int时,它会获取值-2,147,483,648,然后使用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);
}

答案 1 :(得分:0)

根据msdn:Int.Maxvalue的值是2,147,483,647

您的电话号码似乎比这更大。