<

Calculate the month difference between two dates in C#

Published on
21,185 Points
14,885 Views
3 Endorsements
Last Modified:
Approved
Hi,

There are a lot of written methos of getting the difference between two dates, but I couldn't find the one I needed. I need to have a real difference like 3.75 months between the two dates.

Not every month has the same amount of days and the February is also an issue here. So I made myself a method doing this:

/// <summary>
/// Get months difference between two dates
/// </summary>
/// <param name="from">from date</param>
/// <param name="to">to date</param>
/// <returns>months (double) between </returns>
internal static double GetMonths(DateTime from, DateTime to)
{
	/// |-------X----|---------------|---------------|--X-----------|
	///         ^                                       ^
	///       from                                     to

	//change the dates if to is before from
	if (to.Ticks < from.Ticks)
	{
		DateTime temp = from;
		from = to;
		to = temp;
	}

	/// Gets the day percentage of the months = 0...1
	///
	/// 0            1                               0              1
	/// |-------X----|---------------|---------------|--X-----------|
	/// ^^^^^^^^^                                    ^^^^
	/// percFrom                                    percTo
	double percFrom = (double)from.Day / DateTime.DaysInMonth(from.Year, from.Month);
	double percTo = (double)to.Day / DateTime.DaysInMonth(to.Year, to.Month);

	/// get the amount of months between the two dates based on day one
	/// 
	/// |-------X----|---------------|---------------|--X-----------|
	/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	///                        months
	double months = (to.Year * 12 + to.Month) - (from.Year * 12 + from.Month);

	/// Return the right parts
	/// 
	/// |-------X----|---------------|---------------|--X-----------|            
	///         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
	///                      return
	return months - percFrom + percTo;            
}

Open in new window


So what this method does is seeing every month as a number between the 0 and the 1.
It counts the months between the two dates using day=1 and correct this number with the percentages calculated. Using the buit in method for getting the DaysInMonth, you're fine with every month, even February.

Regards,
Erik
3
Author:TGB01
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free