Question

Given the code snippet below, why are the final four output periods the same? I would expect the Days portion for those lines to be 4, 3, 2, 1 not 4, 4, 4, 4. Is this a bug or am I missing something obvious? (It's late and I'm tired, so it's very possibly the latter.) I'm using 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
Was it helpful?

Solution

It's because of how the calculation of the period is done - from Date and Time Arithmetic in Noda Time: "the rule is extremely simple: One component is added at a time, starting with the most significant, and wrapping / truncating at each step."

So when it goes through that February, a truncation to 28 days happens. You can see the same thing happen with a truncation to 30 days if you edit your code to go from (2013, 3, day) to (2013, 5, 4):

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

If you get the period in terms of days only (Period.Between(d1, d2, PeriodUnits.Days)) then you get the expected descending count:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top