If startTime
and endTime
represent a single time interval (it will only happen once, and startTime
and endTime
represent the date and the time to start/stop), then it's as easy as saying
bool isTimeBetween = someTime >= startTime && someTime <= endTime;
If it's a recurring event (happens every day, during some interval), you can do comparisons using the TimeOfDay
property. (The recurring case is the one where you have to consider a start/stop that crosses midnight)
static public bool IsTimeOfDayBetween(DateTime time,
TimeSpan startTime, TimeSpan endTime)
{
if (endTime == startTime)
{
return true;
}
else if (endTime < startTime)
{
return time.TimeOfDay <= endTime ||
time.TimeOfDay >= startTime;
}
else
{
return time.TimeOfDay >= startTime &&
time.TimeOfDay <= endTime;
}
}
(Note: This code assumes that if start == end
, then it covers all times. You made a comment to this effect on another post)
For example, to check if it's between 5 AM and 9:30 PM
IsTimeOfDayBetween(someTime, new TimeSpan(5, 0, 0), new TimeSpan(21, 30, 0))
If startTime
and endTime
are DateTime
s, you could say
IsTimeOfDayBetween(someTime, startTime.TimeOfDay, endTime.TimeOfDay)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…