Noda Time: Period.Between() 01/01/2023 and 31/12/2023 returns 11 months instead of 12

85 Views Asked by At

I am trying to get the number of months between two DateTime objects.

I am using NodaTime. And my two DateTime values are:

  • Start: 01/01/2023
  • End: 31/12/2023

Here's my code:

// period in months between start and end date
LocalDateTime startDate = LocalDateTime.FromDateTime(request.Entity.StartDatetime.Value);
LocalDateTime endDate = LocalDateTime.FromDateTime(request.Entity.FinishDatetime.Value);
Period period = Period.Between(startDate, endDate, PeriodUnits.Months);
int numberOfMonths = period.Months;

I expect numberOfMonths to be 12, but instead, I'm getting 11.

Where am I going wrong?

1

There are 1 best solutions below

3
Enigmativity On BEST ANSWER

Unsurprisingly this code gives 12 months:

LocalDateTime startDate = LocalDateTime.FromDateTime(new DateTime(2023, 1, 1));
LocalDateTime endDate = LocalDateTime.FromDateTime(new DateTime(2024, 1, 1));
Period period = Period.Between(startDate, endDate, PeriodUnits.Months);
int numberOfMonths = period.Months;

The key is that 12 months have actually elapsed.

If you're looking at 2023/12/31 then it's actually 2023/12/31 00:00 and is a day short of 12 months.