Reputation: 31
What is the easiest way to get the difference in months between two dates in C#?
ie: (date1 - date2).TotalMonths .. kind of thing. thanks!
Upvotes: 3
Views: 2746
Reputation: 1
public static int GetMonthDifference(DateTime date1, DateTime date2)
{
if (date1 > date2)
{
DateTime swap = date1;
date1 = date2;
date2 = swap;
}
return ((date2.Year * 12) + date2.Month) - ((date1.Year * 12) + date1.Month);
}
Upvotes: 0
Reputation: 9163
If you don't know how to calculate date span in .net here is good example:
DateTime startTime = DateTime.Now; DateTime endTime = DateTime.Now.AddSeconds(75); TimeSpan span = endTime.Subtract ( startTime ); Console.WriteLine( "Time Difference (seconds): " + span.Seconds ); Console.WriteLine( "Time Difference (minutes): " + span.Minutes ); Console.WriteLine( "Time Difference (hours): " + span.Hours ); Console.WriteLine( "Time Difference (days): " + span.Days );
Source: here.
DateTime don't expose the difference in month since every month have a different number of days. The simplest way to get the month is totaldays / 30
.
Upvotes: 2
Reputation: 15016
The best I can suggest is to get the total number of days, and then roughly compute the number of months by dividing accordingly. Something like:
DateTime dt1 = new DateTime( 2010, 10, 23);
DateTime dt2 = new DateTime( 2010, 7, 23);
TimeSpan ts = dt1 - dt2;
int days_per_month = 30;
Console.Write( ts.TotalDays / days_per_month);
If you really are okay with something like 2010 Feb 1 - 2010 Jan 31 returning 1 month as its answer, then given the above code, you would be able to get at this easily by using
Console.Write( dt1.Month - dt2.Month);
This doesn't take into consideration the year, so I defer to the other answer here that does this. :)
Upvotes: 2
Reputation: 136663
Given the updates you have made to your original question: How about writing up a function that takes two dates and does the following,
DateTime d1 = new DateTime(2008, 12, 1);
DateTime d2 = new DateTime(2009, 1, 1);
var month_diff = (d2.Year - d1.Year)*12 + (d2.Month - d1.Month);
Console.WriteLine(month_diff);
Upvotes: 5
Reputation: 4716
Since you already know that your dates will be the first of the month:
int totalMonths = (date2.Year - date1.Year)*12 + date2.Month - date1.Month;
Upvotes: 4
Reputation: 20956
TimeSpan Class :)
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (months): " + span.Days / 30 );
Upvotes: 0