Quantcast
Channel: Difference in months between two dates - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by George Mavritsakis for Difference in months between two dates

$
0
0

My understanding of the total months difference between 2 dates has an integral and a fractional part (the date matters).

The integral part is the full months difference.

The fractional part, for me, is the difference of the % of the day (to the full days of month) between the starting and ending months.

public static class DateTimeExtensions{    public static double TotalMonthsDifference(this DateTime from, DateTime to)    {        //Compute full months difference between dates        var fullMonthsDiff = (to.Year - from.Year)*12 + to.Month - from.Month;        //Compute difference between the % of day to full days of each month        var fractionMonthsDiff = ((double)(to.Day-1) / (DateTime.DaysInMonth(to.Year, to.Month)-1)) -            ((double)(from.Day-1)/ (DateTime.DaysInMonth(from.Year, from.Month)-1));        return fullMonthsDiff + fractionMonthsDiff;    }}

With this extension, those are the results:

2/29/2000 TotalMonthsDifference 2/28/2001 => 122/28/2000 TotalMonthsDifference 2/28/2001 => 12.03571428571428601/01/2000 TotalMonthsDifference 01/16/2000 => 0.501/31/2000 TotalMonthsDifference 01/01/2000 => -1.001/31/2000 TotalMonthsDifference 02/29/2000 => 1.001/31/2000 TotalMonthsDifference 02/28/2000 => 0.964285714285714301/31/2001 TotalMonthsDifference 02/28/2001 => 1.0

Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>