简体   繁体   English

时间段检查

[英]Time Period Check

I want to check if a given period of time(HH:MM) is within the other one and return true else it shall return false 我想检查给定的时间段(HH:MM)是否在另一个时间内并返回true,否则它将返回false

I have tried this equation 我试过这个等式

 (StartTime_1 <= EndTime_2 && StartTime_2 < EndTime_1)    || 
 (StartTime_1 < StartTime_2 && EndTime_2 <= EndTime_1)

But it seems to measure overlapping rather than any thing, what i want is like this, For example Start_1 is 08:00 AM and End_1 is 10:00 PM, any time that comes between these two it shall return true and any other like (from 09 PM to 08 AM) it shall return false. 但它似乎衡量重叠而不是任何东西,我想要的是这样的,例如Start_1是08:00 AM而End_1是10:00 PM,这两者之间的任何时间它都将返回true和任何其他类似的(从09 PM到08 AM)它将返回false。

There are a number of possible cases. 有许多可能的情况。 在此输入图像描述

To check if they overlap at any point in time, you need to check if the end of the test time period start is before time period 1 end, and if the test time end is after period 1 start. 要检查它们是否在任何时间点重叠,您需要检查测试时间段结束是否在时间段1结束之前,以及测试时间结束是否在时间段1开始之后。

If you have a different description of overlap, you'll have to expand by referencing which lines in the image should be considered in or out. 如果您有不同的重叠描述,则必须通过引用图像中的哪些行进行扩展来进行扩展。

Its hard to tell from your variable names, but it looks like you almost have it right. 从您的变量名称很难说,但看起来你几乎是正确的。 To test for true containment, you just need to always use "and" ( && ): 要测试真正的遏制,您只需要始终使用“和”( && ):

DateTime AllowedStart;
DateTime AllowedEnd;

DateTime ActualStart;
DateTime ActualEnd;

//Obviously you should populate those before this check!
if (ActualStart > AllowedStart && //Check the start time
    ActualStart < AllowedEnd && //Technically not necessary if ActualEnd > ActualStart
    ActualEnd < AllowedEnd &&  //Check the end time
    ActualEnd > AllowedStart) //Technically not necessary if ActualEnd > ActualStart

How about 怎么样

(StartTime_2 >= StartTime_1 && EndTime_2 <= EndTime_1) && (StartTime_1 < EndTime_1) && (StartTime_2 < EndTime_2)

I would think this should do what you're looking for 我认为这应该做你想要的

With this method, I can check if a period (start2 to end2) is contained in another (start1 to end1) 使用这种方法,我可以检查一个句点(start2到end2)是否包含在另一个句子中(start1到end1)

public static Boolean IsContained(DateTime start1, DateTime end1, DateTime start2, DateTime end2)
{
    // convert all DateTime to Int
    Int32 start1_int = start1.Hour * 60 + start1.Minute;
    Int32 end1_int = end1.Hour * 60 + end1.Minute;
    Int32 start2_int = start2.Hour * 60 + start2.Minute;
    Int32 end2_int = end2.Hour * 60 + end2.Minute;

    // add 24H if end is past midnight
    if (end1_int <= start1_int)
    {
        end1_int += 24 * 60;
    }

    if (end2_int <= start2_int)
    {
        end2_int += 24 * 60;
    }

    return (start1_int <= start2_int && end1_int >= end2_int);
}

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

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