假设我有一个名为 NextSend
的属性,表示 DateTime
值
2011 年 4 月 11 日上午 10:30:00 - 星期一
假设我有一个时间表,在这种情况下必须每周在特定日期(星期一)
发送,以便找出下周的时间表我最终得到了解决方案,我必须检查每个下一个日期,直到 DayOfWeek
与时间表中的特定日期
匹配
4/
17/2011 上午 10:30:00 - 星期一
还有其他最好的方法来克服检查每个第二天日期的日期名称吗?
这是我提到的逻辑:
int nowYear = DateTime.Now.Year;
int nowMonth = DateTime.Now.Month;
int nowDay = DateTime.Now.Day;
int scheduleHour = this.Schedule.Time.Value.Hour;
int scheduleMinute = this.Schedule.Time.Value.Minute;
int scheduleSecond = this.Schedule.Time.Value.Second;
int scheduleDay = -1;
if(this.Schedule.Day.HasValue)
scheduleDay= this.Schedule.Day.Value;
switch (type)
{
case Schedule.ScheduleType.Weekly:
bool founded = false;
while (!founded)
{
//Check if last day of the current month
if (DateTime.DaysInMonth(nowYear, nowMonth) == nowDay)
{
//last day at this year, then move to next year
if (nowMonth == 12)
{
nowYear++;
nowMonth = 1;
nowDay = 1;
}
//its the end of a month then Move to next month
else
{
nowMonth++;
nowDay = 1;
}
}
//Get new proposed date
newNextSend = new DateTime(nowYear, nowMonth, nowDay, scheduleHour, scheduleMinute, scheduleSecond);
//Check if Next week schedule founded with specific day name
if (newNextSend.DayOfWeek ==
(DayOfWeek)Enum.Parse(typeof(DayOfWeek), Schedule.daysCalendar[scheduleDay - 1]))
{
founded = true;
}
else
nowDay++;
}
break;
}
最佳答案
正如所有其他人所说:AddDays(7) 将确保每周计划按要求运行。但是,如果您正在寻找一种方法来确定特定工作日的下一次出现,那么您可以执行以下操作:
private static DateTime GetNextDayOccurrence(DayOfWeek day, DateTime startDate)
{
if (startDate.DayOfWeek == day)
{
return startDate;
}
else
{
return GetNextDayOccurrence(day, startDate.AddDays(1));
}
}
然后像这样调用
var nextWednesday = GetNextDayOccurrence(DayOfWeek.Wednesday, DateTime.Today);
将返回第一次出现的星期三。之后每周的计划继续运行。如果您需要从下周开始第一次出现“星期三”,只需传递
DateTime.Today.AddDays(7)
到上述方法的“startDate”参数。
关于c# - 按特定日期名称找出下周时间表的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5620141/