/// <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;
}
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (3)
Commented:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx
Author
Commented:I know, but using this you get the real difference between two dates, like the days between the two dates (Double). In the TimeSpan, there is no Month property.
And in my case, the method is using one month as 100%, so every month can have different amount of days. So the same amount of days between two dates can have multiple results depending on the choosen dates.
Commented:
if you can get the sum right using proper math, you should then be able to recreate the sum in a method \ function and return the value accordingly.