It's a too late answer and as I checked no one answered about the exact fractions of the months like what we have in the TimeSpan.TotalDays
for example.
for example what is the result of total months between 20-01-2021
and 20-03-2021
?
I guess it should be 2.0xx
, but if you considered Feb as 30 days, you'll get a different answer "1.8xx
or something"
So I've done the calculation according to the days in each month between the selected dates.
- First I've got the list of days between the selected two dates as in @mqp answer
- then I grouped them by month and did the calculation
the code:
public static double GetTotalMonths(this DateTimeOffset firstDate, DateTimeOffset thru)
{
var days = firstDate.EachDayTill(thru).ToList();
return days.GroupBy(d => new {d.Month, d.Year,})
.Sum(g => (g.Count() * 1.00) / (DateTime.DaysInMonth(g.Key.Year, g.Key.Month) * 1.00));
}
public static IEnumerable<DateTimeOffset> EachDayTill(this DateTimeOffset from, DateTimeOffset thru)
{
for (var day = new DateTimeOffset(from.Date, TimeSpan.Zero); day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}