Wednesday, June 04, 2008

Calculate Number of Months from a Date

Here is a simple function to calculate number of months from a date to now:

public int NumberOfMonths(DateTime fromDate)
{
int months;
DateTime dt = DateTime.Now;
months = dt.Month + dt.Year * 12 -
(fromDate.Month + fromDate.Year * 12);
return months;
}


It is simple and no need to add any comments. However, when I first tried to google it, I found some very complex codes to get number of months and they are not right. Finally, based those codes, I figured out that the calculation is simple.

You may use this function twice to get difference between two dates.

One note about this function is that if the input date value is a future time, the number of months is a negative value.

0 comments: