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?
Unsurprisingly this code gives 12 months:
The key is that 12 months have actually elapsed.
If you're looking at
2023/12/31then it's actually2023/12/31 00:00and is a day short of 12 months.