Difference between using `Period.Between` and substracting two local dates

Viewed 77

Why is the result for the periodBetween.Days and substracted.Days different? I can see that a periodBetween.Months is 0 and substracted.Months is 2 and I can see how are these two results different, but I don't know why :).

using NodaTime;
void Main()
{
    var firstDate = new LocalDate(2020, 8, 1);
    var secondDate = new LocalDate(2020, 10, 30);
    
    var periodBetween = Period.Between(firstDate, secondDate, PeriodUnits.Days);
    var subtracted = secondDate - firstDate;
    Console.WriteLine(periodBetween.Days);
    Console.WriteLine(subtracted.Days);
}
1 Answers

Your periodBetween calculation is saying "What's the period between these two dates, using only days?"

Your subtracted calculation is equivalent to calling Period.Between either without specifying any units, or specifying PeriodUnits.Days | PeriodUnits.Months | PeriodUnits.Years - in other words, "What's the period between these two dates, using days, months and years?"

A period has independent values for years, months, days, hours, minutes etc - if you compute a value using years/months/days that's not equivalent to computing a value using just days.

A period of "90 days" is not the same as a period of "2 months and 29 days". In some calculations they'll give the same answer, but not always. For example, if you add "90 days" to January 1st 2020, you'll get March 31st 2020... but if you add "2 months and 29 days" to January 1st 2020, you'll get March 30th 2020.

Related