8/07/2009

Function for Calculating Difference between two dates....

This function will calculate the date difference from today to the date passed to this function.

Send it the Date in the form of DateTime in asp.net C#.

int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
DateTime fromDate=DateTime.Now ;
DateTime toDate=dt;
string difference;
int year;
int month;
int day;
int increment = 0;

if (fromDate.Day > toDate.Day)
{
increment = monthDay[fromDate.Month - 1];

}

if (increment == -1)
{
if (DateTime.IsLeapYear(fromDate.Year))
{

increment = 29;
}
else
{
increment = 28;
}
}
if (increment != 0)
{
day = (toDate.Day + increment) - fromDate.Day;
increment = 1;
}
else
{
day = toDate.Day - fromDate.Day;
}


if ((fromDate.Month + increment) > toDate.Month)
{
month = (toDate.Month + 12) - (fromDate.Month + increment);
increment = 1;
}
else
{
month = (toDate.Month) - (fromDate.Month + increment);
increment = 0;
}


year = toDate.Year - (fromDate.Year + increment);
if( year==0 && month==0 && day==0 )
{
if ((DateTime.Now.Hour - toDate.Hour)==0)
{
return difference = ((DateTime.Now.Minute - toDate.Minute) + " m ").ToString();
}
return difference=((DateTime.Now.Hour-toDate.Hour)+" h ").ToString();

It receives data in the form of DateTime.....


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Favorites More