I am making a function to check time fall between a time range in 24hr format, However there is some thing wrong with my code , can any one point out how to fix ?
My code:
bool isDoTime(int starthour, int startminute, int endhour, int endminute)
{
TimeSpan start = new TimeSpan(starthour, startminute, 0);
TimeSpan end = new TimeSpan(endhour, endminute, 0);
TimeSpan add24h = new TimeSpan(24, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
if (starthour > endhour || (endhour == starthour && endminute <= startminute))
{
end += add24h;
}
if ((now > start) && (now < end))
{
return true;
}
return false;
}
Problem: i want to return true when current time between 20:30 – 3:30 , however when i run my code as below. the condition is return true only from 8:30 to 00:00 , not true from 00:00 – 3:30
if (isDoTime(20,30,3,30) //return true from 20:30 - 3:30
{
//dosomething
}
Split up in one check if it spans across midninght, and one for same day.
The short/cryptic version: