Noda Time:Period.Between()返回错误的天数?

时间:2013-12-31 07:20:05

标签: c# nodatime

鉴于下面的代码片段,为什么最后四个输出周期相同?我希望那些行的Days部分是4,3,2,1不是4,4,4,4这是一个bug还是我错过了一些明显的东西? (已经很晚了,我很累,所以很可能是后者。)我正在使用Noda Time 1.2.0。

for (int day = 25; day <= 31; day++)
{
    var d1 = new LocalDate(2013, 12, day);
    var d2 = new LocalDate(2015, 3, 4);

    var period = Period.Between(d1, d2);
    Debug.WriteLine("Day: {0}, Period: {1}", day, period);
}

// I get the following output:
Day: 25, Period: P1Y2M7D
Day: 26, Period: P1Y2M6D
Day: 27, Period: P1Y2M5D
Day: 28, Period: P1Y2M4D
Day: 29, Period: P1Y2M4D
Day: 30, Period: P1Y2M4D
Day: 31, Period: P1Y2M4D

1 个答案:

答案 0 :(得分:4)

这是因为时间的计算是如何完成的 - 来自Date and Time Arithmetic in Noda Time:“规则非常简单:一次添加一个组件,从最重要的开始,并包装/截断在每一步。“

因此,当它经历了那个二月时,截止到28天。如果您编辑代码以从(2013, 3, day)转到(2013, 5, 4),则截断到30天就会发生同样的事情:

Day: 25, Period: P1M9D
Day: 26, Period: P1M8D
Day: 27, Period: P1M7D
Day: 28, Period: P1M6D
Day: 29, Period: P1M5D
Day: 30, Period: P1M4D
Day: 31, Period: P1M4D

如果您仅以天数(Period.Between(d1, d2, PeriodUnits.Days))获得期间,那么您将获得预期的降序数:

Day: 25, Period: P434D
Day: 26, Period: P433D
Day: 27, Period: P432D
Day: 28, Period: P431D
Day: 29, Period: P430D
Day: 30, Period: P429D
Day: 31, Period: P428D