Question

I am making a booking system where users can make appointments with each other. What I need to do is make sure that the meetings do not clash time wise.

For example: Meeting 1 is from 13:00 to 14:00. Meeting 2 is from 13:30 to 14:30.

These meetings clash and therefore the booking should not be made.

Now when I try to do this I am not getting the desired result, sometimes it thinks the booking should not be made when it really should, and vice versa.

Here is my code:

if (OldBookingDate.Equals(NewBookingDate))
                {
                    // Check if (OldBookingTime -> OldEndTime) clashes with (NewBookingTime -> NewEndTime)
                    //  For Example (10:00 -> 12:00), (09:00 -> 11:00)
                    //  So this Clashes!
                    DateTime OldBookingTime_End = OldBookingTime_Start.AddHours(OldDurationInt);
                    DateTime NewBookingTime_End = NewBookingTime_Start.AddHours(NewDurationInt);

                    int Clash1 = OldBookingTime_Start.CompareTo(NewBookingTime_Start);
                    int Clash2 = OldBookingTime_End.CompareTo(NewBookingTime_End);
                    if ((Clash1 < 0) || (Clash2 > 0))
                    {
                        // If Clash1 -> Finishes before Meeting
                        // If Clash2 -> Finishes after Meeting
                        Available = true;
                    }
                    if ((Clash1 == 0) || (Clash2 == 0))
                    {
                        // Start and end is the same
                        Available = false;
                    }
                    if ((Clash1 > 0) || (Clash2 < 0))
                    {
                        // Intersects/Clashes with already booked meeting
                        Available = false;
                    }
                }

The main problem seems to be with the ((Clash1 > 0) || (Clash2 < 0)) if statement as when a booking should be made the first if statement sets available to true (as it should) but then this if statement then sets it to false.

How may I perform these checks properly to make sure the times do not clash?

Was it helpful?

Solution

Try this:

bool clashing = (OldBookingTime_Start <= NewBookingTime_End)
             && (NewBookingTime_Start >= OldBookTime_End);

Available = !clashing;

See also:

Determine Whether Two Date Ranges Overlap

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top