想象一下,我有一个名为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;
}
答案 0 :(得分:3)
正如所有其他人所说: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”参数。
答案 1 :(得分:2)
为什么不在原始日期添加7天?一周中的天数是不变的;)
下周一:
var nextMonday = thisMonday.AddDays(7);
答案 2 :(得分:0)
你不能使用AddDays(7)吗?
e.g。
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;
}
答案 3 :(得分:0)
AddDays
可以自动处理月份和年份包装。