如何计算一个时间段内有几个星期x
比如说: 要计算2001-03-15到2007-02-01之间有几个星期天?
如果答案是逐天判断的话, 就不辛苦您了.
------解决方案--------------------DateTime dt1=DateTime.Parse( "2001-03-15 "),dt2=DateTime.Parse( "2007-02-01 ");
TimeSpan ts = dt2 - dt1;
int countOfSunday = ts.Days / 7;//countOfSunday 星期天数
if (dt1.DayOfWeek==DayOfWeek.Sunday)count++;
if (dt2.DayOfWeek < dt1.DayOfWeek)count++;
------解决方案--------------------private int TotalWeeks(DateTime AStart, DateTime AEnd, DayOfWeek vWeek)
{
TimeSpan vTimeSpan = new TimeSpan(AEnd.Ticks - AStart.Ticks);
int Result = (int)vTimeSpan.TotalDays / 7; // 共几周
for (int i = 1; i < vTimeSpan.TotalDays % 7; i++) // 是否在剩余的日期里出现
if (AStart.AddDays(i).DayOfWeek == vWeek)
return Result + 1;
return Result;
}
private void button1_Click(object sender, EventArgs e)
{
DateTime vStart = DateTime.Parse( "2001-03-15 ");
DateTime vEnd = DateTime.Parse( "2007-02-01 ");
Text = TotalWeeks(vStart, vEnd, DayOfWeek.Sunday).ToString();
}