假设我有一个名为NextSend
的属性,表示DateTime
值
4/11/2011 10:30:00 AM - Monday
假设我有一个必须每周发送特定日期的时间表 (Monday)
在这种情况下,所以为了找出下一个星期的时间表,我最终得到的解决方案是,我必须检查每个下一个日期的一天,直到DayOfWeek
匹配specific day
在时间表
4/
17/2011 10:30:00 AM - Monday
有没有其他最好的方法来克服检查每个第二天日期的日期名称?
下面是我提到的逻辑:
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);
将返回星期三的第一个出现。之后,每周的日程安排继续进行。如果需要下周"Wednesday"第一次出现,只需传递
DateTime.Today.AddDays(7)
为什么不在原来的日期上加7天呢?一个星期的天数是固定的;)
下周一:
var nextMonday = thisMonday.AddDays(7);
- 有一个叫做
AddDays
的方法可以自动处理月份和年份。 - 周总是7天长。只需添加当前星期几与计划星期几之间的差值。
不能使用AddDays(7)吗?
。
DateTime nextSheduleDate = scheduleDateTime.AddDays(7);
这是Tobias答案的非递归版本。使用Daniel提到的逻辑
public static DateTime GetNextDayOccurrence(DateTime startDate, DayOfWeek dayOfWeek)
{
var offset = startDate.DayOfWeek > dayOfWeek ? 7 : 0;
var days = (int) dayOfWeek + offset - (int) startDate.DayOfWeek;
var dateTime = startDate.AddDays(days);
return dateTime;
}