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

Answer by EgoPingvina for Difference in months between two dates

$
0
0

Someone must have done it))

The extension method returns the number of full months between the given dates. No matter in what order the dates are received, a natural number will always be returned.No approximate calculations as in the "correct" answer.

    /// <summary>    /// Returns the difference between dates in months.    /// </summary>    /// <param name="current">First considered date.</param>    /// <param name="another">Second considered date.</param>    /// <returns>The number of full months between the given dates.</returns>    public static int DifferenceInMonths(this DateTime current, DateTime another)    {        DateTime previous, next;        if (current > another)        {            previous = another;            next     = current;        }        else        {            previous = current;            next     = another;        }        return            (next.Year - previous.Year) * 12     // multiply the difference in years by 12 months+ next.Month - previous.Month          // add difference in months+ (previous.Day <= next.Day ? 0 : -1); // if the day of the next date has not reached the day of the previous one, then the last month has not yet ended    }

But if you still want to get the fractional parts of the months, you just need to add one more term to the return:

+ (next.Day - previous.Day) / DateTime.DaysInMonth(previous.Year, previous.Month)


Viewing all articles
Browse latest Browse all 46

Trending Articles



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