为什么 DateTime.AddDays 四舍五入到最接近的毫秒

本文关键字:最接近 DateTime AddDays 四舍五入 为什么 | 更新日期: 2023-09-27 18:31:09

我在 .NET 中除以两个双精度,并使用结果对象通过调用(dtStart 是预定义的)从开始日期计算出结束日期:

var dValue = 1500.0/8400.0;
var dtEnd = dtStart.AddDays(dValue);

检查dtEnd后,我发现结果只精确到最接近的毫秒。查了一下后,我发现.AddMilliseconds等都绕着这个数字,TimeSpan.FromDays也做了类似的事情。我想知道进行这种四舍五入是否有原因,因为似乎在这里获得正确值的唯一方法是使用 .添加刻度?

供参考。添加天数调用(其中 MillisPerDay = 86400000)

public DateTime AddDays(double value) 
{
    return Add(value, MillisPerDay);
}

哪个调用

private DateTime Add(double value, int scale) 
{
    long millis = (long)(value * scale + (value >= 0? 0.5: -0.5));
    if (millis <= -MaxMillis || millis >= MaxMillis) 
    throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
    return AddTicks(millis * TicksPerMillisecond);
}

为什么 DateTime.AddDays 四舍五入到最接近的毫秒

编辑:经过思考,我现在意识到我的答案的第一个版本是错误的。

以下是Microsoft源代码中的注释:

// Returns the DateTime resulting from adding a fractional number of
// xxxxs to this DateTime. The result is computed by rounding the
// fractional number of xxxxs given by value to the nearest
// millisecond, and adding that interval to this DateTime. The
// value argument is permitted to be negative.

这些注释出现在五种不同的 AddXxxxs(双值)方法上,其中 Xxxx = 天、小时、毫秒、分钟和秒。

请注意,这仅适用于接受浮点值的方法。(有人可能会质疑在日期计算中涉及浮点值是否是一个好主意 - 但这是另一天的主题。

现在,正如 OP 正确指出的那样,这五种方法都调用此方法:

// Returns the DateTime resulting from adding a fractional number of
// time units to this DateTime.
private DateTime Add(double value, int scale) {
    long millis = (long)(value * scale + (value >= 0? 0.5: -0.5));
    if (millis <= -MaxMillis || millis >= MaxMillis) 
        throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
    return AddTicks(millis * TicksPerMillisecond);
}

因此,正在做的是,添加到日期时间的值在添加之前四舍五入到最接近的毫秒数。但不是结果 - 只有被添加(或减去)的值。

这实际上是有记录的,例如 http://msdn.microsoft.com/en-us/library/system.datetime.adddays%28v=vs.110%29.aspx"value 参数四舍五入到最接近的毫秒"。

我不知道

为什么会这样做。也许程序员认为,如果你使用浮点值,你应该意识到你的值通常并不完全准确。或者,也许他们想在某种程度上模拟基于毫秒的Java风格的时间。