2

Assume I've got a start and stop hour in which some processing should take place:

Start 20:00 End 07:00

Now what is the best algorithm to check if a certain DateTime hour value falls within this range? Thanks in advance!

Please note that the start and end times mentioned above indicate that we are dealing with an "overnight-job". Meaning that the period to be checked starts at 20:00 in the evening and ends at 07:00 on the following morning.

3
  • How do you know that End is only 1 day ahead? And what about if End is say 22:00. Is that same day as Start or is that the next day at 10pm?
    – user7116
    Mar 1, 2010 at 15:09
  • Even just overnight can span end-of-month and end-of-year boundaries.
    – mpez0
    Mar 1, 2010 at 21:48
  • Your edit completely changed the question - so many of the answers to the original question are no longer relevant.
    – KevinDTimm
    Mar 4, 2010 at 4:03

10 Answers 10

6

Assume you only have the time and not the date.

if end_time >= start_time:
    return start_time <= current_time <= end_time
else:
    return start_time <= current_time or current_time <= end_time
0
3

If you are sure it is in the same day

you also do not seem to care for seconds

Transform everything in minutes

startminute = 20 * 60 + 0
endminute = 7 * 60 + 0
eventminute = x * 60 + y // with event having the form xx:yy
return startminute < eventminute && eventminute < endminute 

Another option would be to get the 3 times in DateTime format

DateTime start, end, event

return (start < event && event < end);
2
  • The shown example in my post indicates, that this is an "overnight" job (starting today at 20:00 and ending tomorrow at 07:00 in the morning). So I guess your solution won't work well. Thanks anyway! (btw, I've updated the question to clarify)
    – Mats
    Mar 1, 2010 at 14:03
  • But, your edit was after this answer - so withdrawing the question and re-asking would be better
    – KevinDTimm
    Mar 4, 2010 at 4:04
1

Assuming you have a start, end and now DateTime, you could use

bool within = start.TimeOfDay.TotalHours <= now.TimeOfDay.TotalHours && 
              now.TimeOfDay.TotalHours <= end.TimeOfDay.TotalHours;
0

Without knowing how to do it in C#, I'd go with converting start and end time to a timestamp and then do a simple if (end time >= given time AND start time <= given time) comparison. Maybe that'll get you started or give you a hint what to search for.

0

I think c# supports greater than/less than operators for DateTime variables, so just say

if ((beginDateTime<myDateTime)&&(myDateTime<endDateTime))
{
    ...
}

Also greater than or equal to and less than or equal to are supported.

0

With an overnight window, I don't think there's anything particularly clever to be done except to directly check your DateTime's TimeOfDay against the boundaries:

using System;

namespace Question2355777
{
    class Program
    {    
        private static bool IsInOvernightWindow(
            DateTime dateTimeUnderTest, 
            TimeSpan morningEnd, 
            TimeSpan eveningStart)
        {
            TimeSpan timeOfDay = dateTimeUnderTest.TimeOfDay;
            return timeOfDay <= morningEnd || timeOfDay >= eveningStart;
        }

        static void Main(string[] args)
        {
            TimeSpan eveningStart = TimeSpan.FromHours(20);
            TimeSpan morningEnd = TimeSpan.FromHours(7);

            Console.WriteLine("{0} {1}", 
                DateTime.Today.AddHours(3),
                IsInOvernightWindow(
                    DateTime.Today.AddHours(3), 
                    morningEnd, 
                    eveningStart));

            Console.WriteLine("{0} {1}", 
                DateTime.Today.AddHours(12),
                IsInOvernightWindow(
                    DateTime.Today.AddHours(12), 
                    morningEnd, 
                    eveningStart));

            Console.WriteLine("{0} {1}", 
                DateTime.Today.AddHours(21),
                IsInOvernightWindow(
                    DateTime.Today.AddHours(21), 
                    morningEnd, 
                    eveningStart));

            Console.ReadLine();
        }
    }
}

produces

01/03/2010 03:00:00 True
01/03/2010 12:00:00 False
01/03/2010 21:00:00 True
0
// initializing with some sample values
TimeSpan start = TimeSpan.FromHours(20);
TimeSpan end = TimeSpan.FromHours(7);
DateTime now = DateTime.Now.TimeOfDay;

return start<end
    ? start <= now.TotalHours && now.TotalHours <= end
    : start <= now.TotalHours || now.TotalHours <= end;
0

Use the TimeOfDay method:

DateTime dtStart = new DateTime(0,0,0,20,0,0);
DateTime dtEnd = new DateTime(0,0,0,7,0,0);

if (DateTime.Now.TimeOfDay < dtEnd.TimeOfDay || DateTime.Now.TimeOfDay > dtStart.TimeOfDay)
{
    // your code here
}
1
  • This doesn't work for basic cases. Such as the time is 17:00, and you want to run between 15:00 and 16:00. In that case your if should be false, but since you or the values your if is true (17 is greater than the start)
    – devshorts
    Nov 6, 2013 at 18:32
0

Count all the times in units of minutes beginning from the start day.

struct DateTime {
  uint_8 hour_;
  uint_8 minute_;
};

bool
isTimeWithin( DateTime start, DataTime stop, DateTime query ) {

  // The following times are counted from the beginning of start day

  uint_16 startInMins = (60 * start.hour_ + start.minute_);

  // Added 24*60 since "stop" is always "overnight" from "start"
  uint_16 stopInMins = 24 * 60 + (60 * stop.hour_ + stop.minute_); 

  // The ternary operator checks whether "query" is in the same day as
  // "start" or the next day
  uint_16 queryInMins = (query.hour_ < start.hour_ ? 24 * 60 : 0 ) + 
                           (60 * query.hour_ + query.minute_); 

  return ((startInMins <= queryInMins) && (queryInMins <= stopInMins));

}

EDIT: Improved Formatting.

0

if ALL you have are those values for start and stop, don't you have an empty set?

Ignore the obvious assumption - start day X, end day X + Y.

[edit]
since the question has been edited, so shall be the answer....
for start time, end time and 'test' time get the number of milliseconds from the epoch
(define that any way you would like)
and then check to see if test is >= start and <= end
[/edit]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.