mukeshsalaria01 mukeshsalaria01 - 5 months ago 31
jQuery Question

Determine Whether Two Date Ranges Overlap, if yes how do I get the overlapped time with new start and end time

I am using jquery full calendar to show events. It's working fine, but I have a scenario where I have to show the availability of person by subtracting his busy time.

So I have two type of events with start and end date
1. person busy time events
2. person available time events

Example : if a person is available 9am-5pm, but he is busy 11am-3pm. Now overlap is occurring from 11am-3pm, now I would like to split it should return me two new events by minus his busy time from the available time. It would return me two new events one from 9am-11am and second one from 3pm-5pm. How do I get this

public bool Intersects(DateTime r1start, DateTime r1end, DateTime r2start, DateTime r2end)
{
return (r1start == r2start) || (r1start > r2start ? r1start <= r2end : r2start <= r1end);
}


Now as I'm able to get overlap if happening, but now I would like to split that overlap and create new events with start and end time.

Any help would be appreciated.

Answer

You can use this implementation of the DateRange :

public class DateRange : IEquatable<DateRange>
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public DateRange Intersect(DateRange d)
    {
        var s = (d.Start > this.Start) ? d.Start : this.Start; // Later Start
        var e = (d.End < this.End) ? d.End : this.End; // Earlier ending

        if (s < e)
            return new DateRange() { Start = s, End = e };
        else
            return null;
    }

    public bool Contains(DateTime d)
    {
        return d >= Start && d <= End;
    }

    public bool Equals(DateRange obj)
    {
        return Start.Equals(obj.Start) && End.Equals(obj.End);
    }
}

EDIT

var d1 =new DateRange() { Start = DateTime.Now, End = DateTime.Now.AddDays(1) };
var d2 =new DateRange() { Start = DateTime.Now.AddDays(-1), End = DateTime.Now };

Console.WriteLine(d1.Intersect(d2));

EDIT2

    public List<DateRange> Intersect2(DateRange d)
    {
        var s = (d.Start > this.Start) ? d.Start : this.Start; // Later Start
        var e = (d.End < this.End) ? d.End : this.End; // Earlier ending

        if (s < e)
            return new List<DateRange>()
            {
                new DateRange() { Start = new DateTime(Math.Min(Start.Ticks, d.Start.Ticks)), End = s },
                new DateRange() { Start = e, End = new DateTime(Math.Max(End.Ticks, d.End.Ticks)) }
            };
        else
            return null;
    }
Comments