简体   繁体   中英

Check if the current time fall in range with different date in C#

i want to check the time that falls into two different date. assume that i need to check from 10:30pm from this day up to 7am of tomorrow.

TimeSpan NightShiftStart = new TimeSpan(22, 30, 0);//10:30pm 
TimeSpan NightShiftEnd = new TimeSpan(7, 0, 0); //7am

and compare it

if ((now > NightShiftStart ) && (now < NightShiftEnd )){}

timespan wont work on this i also tried

DateTime t1 = DateTime.Today.AddHours(22);
DateTime t2 = DateTime.Today.AddDays(1).AddHours(7);

still no luck.

You can use the TimeOfDay property and use that instead. So your code should look like this

if (now.TimeOfDay > NightShiftStart || now.TimeOfDay < NightShiftEnd ){}

EDIT: While the above code is fine for what you asked, this way is a bit more generic and works for all kinds of shifts, as long as you know when they start and end:

TimeSpan ShiftStart = new TimeSpan(22, 30, 0);//10:30pm 
TimeSpan ShiftEnd = new TimeSpan(7, 0, 0); //7am

if ((ShiftStart > ShiftEnd && (now.TimeOfDay > ShiftStart || now.TimeOfDay < ShiftEnd))
   || (now.TimeOfDay > ShiftStart && now.TimeOfDay < ShiftEnd))
{
    // ...
}

Usually you should use >= or <= for comparing either ShiftStart or ShiftEnd as you want an exact time to also fall into one of your shifts.

Try this, It is a simple but effective way:

private bool CheckIfTimeIsBetweenShift(DateTime time)
{
    var NightShiftStart = new TimeSpan(22, 30, 0); 
    var NightShiftEnd = new TimeSpan(7, 0, 0);

    return NightShiftStart <= time.TimeOfDay && time.TimeOfDay >= NightShiftEnd;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM