1

After thinking round about two hours on it, i hope you guys can help me on this one.

I want to build is a calendar-like system where the user isn’t able to add an entry if another entry falls or crosses in the same .TimeOfDay.

So I want to compare two dates (DateTime) To be more specific: the date is just the same just different .TimeofDay

Example:

(Existing entry)
DateTime dateStart:    05/05/2021 17:00
DateTime  dateEnd:     05/05/2021 18:00

(User wants to add this:)
DateTime  compareStart:  05/05/2021 16:30
DateTime  compareEnd:    05/05/2021 17:15

What i want to archieve is to compare if the compareStart + compareEnd crosses the dateStart and dateEnd in any possible way.

SideNote:

compareStart could be 05/05/2021 17:25 and compareEnd could be 05/05/2021 18:30 etc.

It should be only possible to add an entry if there isn’t any any that falls or crosses existing ones. I hope i’ve described my problem clear.

Any advises are welcome

thanks in advance!

ElAlejandro
  • 43
  • 1
  • 6
  • 2
    Does this answer your question? [Determine Whether Two Date Ranges Overlap](https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap) – Heretic Monkey May 05 '21 at 12:30

1 Answers1

2

There are four different overlapping cases that can occure (excuse my Paint skills)

And all of them four have the following in common:

Existing.StartDate <= New.EndDateDate and Existing.EndDate >= New.StartDate

enter image description here

Simplified class:

public class Event
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

two events compared

bool isOverlapping = e1.StartDate <= e2.EndDate && e1.EndDate >= e2.StartDate;

or in a method for a real world example e.g. a calender with a list of existing events comparing with a new one before inserting

public boolAddEvent(List<Event> events, Event newEvent)
{
    if (!events.Any(x => x.StartDate <= newEvent.EndDate && x.EndDateDate >= newEvent.StartDate))
    {
        events.Add(newEvent);
        return true
    }
    else
    {
        return false;
    }
}
fubo
  • 44,811
  • 17
  • 103
  • 137