net获取两个日期之间的天数和工作日数总结
//获取两个日期间的天数(无时间)
DateTime dt1 = Convert.ToDateTime("2008-7-22");
DateTime dt2 = Convert.ToDateTime("2009-7-30");
TimeSpan ts = (TimeSpan)(dt2 - dt1);
Response.Write(ts.TotalDays.ToString());
//获取两个日期间的天数(含时间)
DateTime dt1 = Convert.ToDateTime("2008-7-22 10:12:55");
DateTime dt2 = Convert.ToDateTime("2009-7-30 10:12:54");
System.TimeSpan ts = dt2.Subtract(dt1);
Response.Write(ts.Days.ToString());
//获取两个日期之间的工作日数(自定义方法)
public void getDays()
{
DateTime dt1 = Convert.ToDateTime("2010-12-06 08:00:00");//初始化一个日期
DateTime dt2 = DateTime.Now;//获取今天日期
System.TimeSpan ts = dt2.Subtract(dt1);//TimeSpan得到dt1和dt2的时间间隔
int countday = ts.Days;//获取两个日期间的总天数
int weekday = 0;//工作日
//循环用来扣除总天数中的双休日
for (int i = 0; i < countday; i++)
{
DateTime tempdt = dt1.Date.AddDays(i);
if (tempdt.DayOfWeek != System.DayOfWeek.Saturday && tempdt.DayOfWeek != System.DayOfWeek.Sunday)
{
weekday++;
}
}
Response.Write("总天数:" + countday.ToString());
Response.Write("工作日:" + weekday.ToString());
}