Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if time falls in designated hour range

Tags:

c#

I am new at C#. I'd like to check whether a time is between 2 given hours, and if so then do something. Can anyone give me an example?

pseudocode example:

int starthour = 17;
int endhour = 2;

if ( hour between starthour and endhour){
    dosomething();
}

How do I write a check on whether hour is between starthour and endhour? In C#, the time is returned in AM/PM format so I don't know if it will understand the 17 number as "5 PM".

like image 540
Kellyh Avatar asked Nov 28 '22 18:11

Kellyh


1 Answers

Assuming you're talking about the current time, I'd do something like this:

// Only take the current time once; otherwise you could get into a mess if it
// changes day between samples.
DateTime now = DateTime.Now;
DateTime today = now.Date;
DateTime start = today.AddHours(startHour);
DateTime end = today.AddHours(endHour);

// Cope with a start hour later than an end hour - we just
// want to invert the normal result.
bool invertResult = end < start;

// Now check for the current time within the time period
bool inRange = (start <= now && now <= end) ^ invertResult;
if (inRange)
{
    DoSomething();
}

Adjust the <= in the final condition to suit whether you want the boundaries to be inclusive/exclusive.

If you're talking about whether a time specified from elsewhere is within a certain boundary, just change "now" for the other time.

like image 133
Jon Skeet Avatar answered Dec 10 '22 12:12

Jon Skeet