确定两个日期范围是否重叠,如果是,我如何获得新的开始和结束时间的重叠时间 [英] Determine Whether Two Date Ranges Overlap, if yes how do I get the overlapped time with new start and end time
问题描述
我正在使用jquery完整日历来显示事件。它工作正常,但我有一个场景,我必须通过减去他的繁忙时间来显示人的可用性。
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.
所以我有两种类型的事件,包括开始和结束date
1. person busy time events
2. person available time events
So I have two type of events with start and end date 1. person busy time events 2. person available time events
示例:如果有人在上午9点至下午5点可用,但他是上午11点至下午3点忙。现在重叠是从上午11点到下午3点发生的,现在我想分开它应该通过减去他可用时间的繁忙时间给我两个新事件。它将在早上9点至11点之间返回两个新事件,第二个从下午3点至下午5点返回。我怎么得到这个
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.
推荐答案
您可以使用DateRange的这种实现:
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);
}
}
编辑
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;
}
这篇关于确定两个日期范围是否重叠,如果是,我如何获得新的开始和结束时间的重叠时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!