In my case it is required to calculate the complete month from the start date to the day prior to this day in the next month or from start to end of month.
Ex: from 1/1/2018 to 31/1/2018 is a complete month
Ex2: from 5/1/2018 to 4/2/2018 is a complete month
so based on this here is my solution:
public static DateTime GetMonthEnd(DateTime StartDate, int MonthsCount = 1){ return StartDate.AddMonths(MonthsCount).AddDays(-1);}public static Tuple<int, int> CalcPeriod(DateTime StartDate, DateTime EndDate){ int MonthsCount = 0; Tuple<int, int> Period; while (true) { if (GetMonthEnd(StartDate) > EndDate) break; else { MonthsCount += 1; StartDate = StartDate.AddMonths(1); } } int RemainingDays = (EndDate - StartDate).Days + 1; Period = new Tuple<int, int>(MonthsCount, RemainingDays); return Period;}
Usage:
Tuple<int, int> Period = CalcPeriod(FromDate, ToDate);
Note: in my case it was required to calculate the remaining days after the complete months so if it's not your case you could ignore the days result or even you could change the method return from tuple to integer.