Thursday, August 6, 2009

Difference between two dates as x month and y days.

If you have to find the difference between two dates as x month and y days .

Let the two dates be "StartDate" and "EndDate" and x be the month and y be the days after taking difference between StartDate and EndDate.
int x,y;
x= MonthDifference(StartDate,EndDate);

where MonthDifference(startDate,EndDate) is a function :

public int MonthDifference(DateTime startDate, DateTime endDate)
{
int noOfYears = endDate.Year - startDate.Year;
int noOfMonths = (endDate.Month - startDate.Month);
noOfMonths = noOfMonths + (noOfYears * 12);
return noOfMonths;
}


//To calculate No of Days and Month ..


if (System.DateTime.DaysInMonth(EndDate.Year, EndDate.Month)== (EndDate.Day - StartDate.Day + 1))

{
x = x+ 1;
y = 0;
}
else
{
if(EndDate.Day < StartDate.Day)
{
y = System.DateTime.DaysInMonth(user.EndDate.AddMonths(-1).Year,
user.EndDate.AddMonths(-1).Month) -
StartDate.Day + EndDate.Day + 1;
x = x - 1;
}
else
{
y= EndDate.Day -StartDate.Day + 1;
}
}


In this way you can get the difference between two dates as x month and y days.

Thanks
Varun

No comments:

Post a Comment