Calculate number of months between two dates

Here is the function to calculate months between two dates –

        public static double GetMonths(DateTime from, DateTime to)
        {
            if (to.Ticks < from.Ticks)
            {
                DateTime temp = from;
                from = to;
                to = temp;
            }

            double percFrom = (double)(from.Day-1) / DateTime.DaysInMonth(from.Year, from.Month);
            double percTo = (double)to.Day / DateTime.DaysInMonth(to.Year, to.Month);

            double months = (to.Year * 12 + to.Month) - (from.Year * 12 + from.Month);
            return months - percFrom + percTo;
        }
Advertisements
Posted in Uncategorized. Leave a Comment »