public static int DateDiff(DateTime beginDate, DateTime endDate)
{
TimeSpan diff = endDate.Date - beginDate.Date;
return diff.Days ;
if(beginDate.Date <= endDate.Date)
{
return GetDateTimes(beginDate,endDate).Length;
}
else
{
return -GetDateTimes(beginDate,endDate).Length;
}
//以下是另一种算法;
// FromOADate()方法的日期零点值为1899年12月30日0点0分0秒0毫秒,顺逆推为加减一天
DateTime littleDate = beginDate;
DateTime bigDate = endDate;
bool changed = false;
if (littleDate > bigDate)
{
DateTime md = littleDate;
littleDate = bigDate;
bigDate = md;
changed = true;
}
if(littleDate < Convert.ToDateTime("1899-12-30") )
{
return -1; //只比较1899-12-30之后的日期
}
string lstring = littleDate.ToString("d");
string bstring = bigDate.ToString("d");
string strCurDate,strOthDate;
double i=0, j=0; //可以不从0开始,以减少循环次数
do
{
i ;
strCurDate=DateTime.FromOADate(i).ToString("d");
}
while(strCurDate != lstring );
strOthDate = strCurDate;
while(strOthDate != bstring)
{
j ;
i ;
strOthDate=DateTime.FromOADate(i).ToString("d");
}
if (changed == true)
{
j = -j;
}
return Convert.ToInt32(j);
}
上面列出三种算法.第二种算法还需要GetDateTimes函数的支持,这个函数是返回一个由两日期之间的日期组成的数组。如果用哪种算法可以把另外两种算法注掉。