Example: if two dates are indicated below, the finish is always greater than or equal to the start
start = 2001 January 01
finish = 2002 Mar 15
So, from 2001 January 01 to the end of February February
months = 12 + 2 = 14
In March 2002
15/30 = 0.5
so the total amount is 14.5 months.
Itβs very easy to understand the hand, but how can I prescribe it? At the moment, I have a lot of combinations, if also while loops to achieve what I want, but I believe that there are simpler solutions.
Update: the output should be accurate (not approximation), for example: if the beginning of January 2001 is 01 and 2001 ends April 16, the output should be 1 + 1 + 1 = 3 (for January, February and March) and 16/31 = 0.516 months , so the total number is 3.516.
Another example would be if I start in 2001 on July 5 and finish in 2002 on July 10, the release should be 11 months before the end of June 2002 and (31-5) / 31 = 0.839 and 10/31 = 0.323 months, therefore the total value is 11 + 0.839 + 0.323 = 12.162.
I have expanded the Josh Stodola code and the Hightechrider code :
public static decimal GetMonthsInRange(this IDateRange thisDateRange) { var start = thisDateRange.Start; var finish = thisDateRange.Finish; var monthsApart = Math.Abs(12*(start.Year - finish.Year) + start.Month - finish.Month) - 1; decimal daysInStartMonth = DateTime.DaysInMonth(start.Year, start.Month); decimal daysInFinishMonth = DateTime.DaysInMonth(finish.Year, finish.Month); var daysApartInStartMonth = (daysInStartMonth - start.Day + 1)/daysInStartMonth; var daysApartInFinishMonth = finish.Day/daysInFinishMonth; return monthsApart + daysApartInStartMonth + daysApartInFinishMonth; }
Jeff
source share