This simple static function calculates the fraction of months between two Datetimes, e.g.
- 1.1. to 31.1. = 1.0
- 1.4. to 15.4. = 0.5
- 16.4. to 30.4. = 0.5
- 1.3. to 1.4. = 1 + 1/30
The function assumes that the first date is smaller than the second date. To deal with negative time intervals one can modify the function easily by introducing a sign and a variable swap at the beginning.
public static double GetDeltaMonths(DateTime t0, DateTime t1){ DateTime t = t0; double months = 0; while(t<=t1) { int daysInMonth = DateTime.DaysInMonth(t.Year, t.Month); DateTime endOfMonth = new DateTime(t.Year, t.Month, daysInMonth); int cutDay = endOfMonth <= t1 ? daysInMonth : t1.Day; months += (cutDay - t.Day + 1) / (double) daysInMonth; t = new DateTime(t.Year, t.Month, 1).AddMonths(1); } return Math.Round(months,2); }