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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With