简体   繁体   English

如果两个 DateTime.TimeOfDay 以任何方式交叉,则比较它们。 ASP C#

[英]Comparing two DateTime .TimeOfDay if they crosses in any way. ASP C#

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.我要构建的是一个类似日历的系统,如果另一个条目在相同的 TimeOfDay 中落下或交叉,用户将无法添加条目。

So I want to compare two dates (DateTime) To be more specific: the date is just the same just different.TimeofDay所以我想比较两个日期(DateTime)更具体地说:日期相同只是不同。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.我想要归档的是比较 compareStart + compareEnd 是否以任何可能的方式跨越 dateStart 和 dateEnd 。

SideNote:边注:

compareStart could be 05/05/2021 17:25 and compareEnd could be 05/05/2021 18:30 etc. compareStart 可能是 05/05/2021 17:25, compareEnd 可能是 05/05/2021 18:30 等。

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!提前致谢!

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 Existing.StartDate <= New.EndDateDateExisting.EndDate >= New.StartDate

在此处输入图像描述

Simplified class:简化 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 eg 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM