1

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.

1
  • Can you show your code for testing with DateTime as that should work. Thought you forgot AddMinutes(30). Also if you are always working with todays dates then you really only want to know if the time is after 10:30 pm since it's never tomorrow. Commented Jan 5, 2017 at 17:55

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

You need || instead of &&.
oh thanks didn't really think about it, but I guess you should also check if start is below end and treat it differently
That's not really comparing to tomorrow at 7am, just if it's before 7am regardless of the date.
thank you for the quick response and it was working well now. i didnt think about changing the AND to OR. but the problem its not taking the date.
@Denver I've made an edit to my code so it will work for all shifts/time checks not just the night shift
|
0

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;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.