我需要运行一个作业/调度程序,它应该只更新数据库中在指定时间范围内的记录。在我的例子中,时间范围是从凌晨 3 点 30 分到第二天凌晨 1 点 30 分。因此,在此时间范围内,作业需要更新记录。为了获得这个时间间隔,我使用了 TimeOfDay() 函数,但是我的逻辑失败了,因为如果当前时间是早上 6 点,那么“currentTime <= todaysJob.ENDTIME.Value.TimeOfDay”返回 false。我正在使用下面的代码来检查
var currentTime = DateTime.Now.TimeOfDay;
if (currentTime > todaysJob.STARTTIME.Value.TimeOfDay &&
currentTime <= todaysJob.ENDTIME.Value.TimeOfDay)
{
// Do logic
}
最佳答案
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
}
编辑
所以我补充说:
- 一个 bool 标志,决定任务是否应该在第二天结束
- 一个日期时间变量 (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 枚举出现问题
关于c# - 确定时间范围内的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12208996/