我想做一个课程安排程序。例如,周五的课程相同,应该在调度程序上显示。我怎样才能在一年中获得周五的所有日期? 我有一些数据字段;
-Dayofweek int
-Starthour int
-finishhour int
答案 0 :(得分:0)
就像这样,通知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());
}
}
答案 1 :(得分:0)
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