bool endTomorrow = true;
DateTime taskDate = new DateTime(2012, 08, 31);
TimeSpan Start = new TimeSpan(03, 30, 00);
TimeSpan End = new TimeSpan(01, 30, 00);
DateTime currentTime = DateTime.Now;
bool flag = false;
if (currentTime.TimeOfDay >= Start)
{
if (endTomorrow)
{
flag = currentTime.Date <= taskDate || (currentTime.Date == taskDate.AddDays(1) && currentTime.TimeOfDay < End);
}
else
{
flag = currentTime.TimeOfDay < End;
}
}
if (flag)
{
//do the task
}
编辑
所以我补充说:
- 一个布尔标志,确定任务是否应该在第二天结束
- 表示任务日期的日期时间变量 (taskDate)
Start 和 End 等于 todaysJob.STARTTIME 和 todaysJob.ENDTIME,因此您可以照原样从 DB 中获取它们。
编辑
如果你能有这样的工作:
public class Job
{
public TimeSpan STARTTIME;
public TimeSpan ENDTIME;
public DayOfWeek taskDayOfWeek;
public bool IsEndingTommorow;
public bool IsTomorrow(DayOfWeek d)
{
if (d == DayOfWeek.Sunday)
return taskDayOfWeek == DayOfWeek.Saturday;
else
return d <= taskDayOfWeek;
}
}
那么你可以
DateTime currentTime = DateTime.Now;
bool flag = false;
if (currentTime.TimeOfDay >= todaysJob.STARTTIME)
{
if (todaysJob.IsEndingTommorow)
{
flag = currentTime.DayOfWeek == todaysJob.taskDayOfWeek || (todaysJob.IsTomorrow(currentTime.DayOfWeek) && currentTime.TimeOfDay < todaysJob.ENDTIME);
}
else
{
flag = currentTime.TimeOfDay < todaysJob.ENDTIME;
}
}
if (flag)
{
//do the task
}
编辑
我再次编辑了我的代码:添加了一种方法来避免 DayOfWeek 枚举出现问题