我想做一个课程调度器。例如,所有星期五的课程都相同,应该在调度程序上显示。我怎样才能得到一年中所有星期五的日期?我有一些数据字段;
-Dayofweek int
-Starthour int
-finishhour int
就是这样,注意365可能是366。你可以判断一下。。
DateTime dt=DateTime.Parse(DateTime.Now.ToString("yyyy-01-01"));
for (int i = 0; i < 365;i++ )
{
if (dt.AddDays(i).DayOfWeek==DayOfWeek.Friday)
{
Console.WriteLine(dt.AddDays(i).ToShortDateString());
}
}
static IEnumerable<DateTime> GetAllDaysInYearByDayOfWeek(int year, DayOfWeek dayOfWeek)
{
var startOfYear = new DateTime(year, 1, 1);
var firstMatchingDate = startOfYear.AddDays((dayOfWeek - startOfYear.DayOfWeek + 7) % 7);
for (var dt = firstMatchingDate; dt.Year == year; dt = dt.AddDays(7))
yield return dt;
}
例如:
var fridays = GetAllDaysInYearByDayOfWeek(2013, DayOfWeek.Friday);
foreach (DateTime day in fridays)
Console.WriteLine(day.ToShortDateString());
结果:
01/04/2013
01/11/2013
01/18/2013
...
12/13/2013
12/20/2013
12/27/2013