编程语言
首页 > 编程语言> > c# – Noda Time:Period.Between()返回错误的天数?

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

作者:互联网

鉴于下面的代码片段,为什么最后四个输出周期相同?我希望那些行的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

解决方法:

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

因此,当它经历了那个二月时,会发生截断到28天.如果编辑代码从(2013年,3天,日)到(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

标签:c,nodatime
来源: https://codeday.me/bug/20190624/1280752.html