【问题标题】:time period in time period (PHP)时间段中的时间段 (PHP)
【发布时间】:2014-07-19 10:31:43
【问题描述】:

我试图找出一个时间段是否在一个时间段内。我有我的参考时间段和比较时间段。 我举个例子:

  • 时间段 A(参考)从 1.1.2014 到 1.2.2014 (tt.mm.yyyy)。
  • 时间段 B(比较)从 1.4.2014 到 1.5.2014。

=> 这完全没问题。

  • 时间段 C(参考)从 1.1.2014 到 1.3.2014
  • 时间段 D(比较)从 1.2.2014 到 1.5.2014。

=> 不行,因为 D 在 C 中。

我希望你能得到我想要的。我试图让 serval if 动作,但这开始变得巨大而缓慢。也许有更快的方法来做到这一点。

另外,MySQL 能做到这些吗?

【问题讨论】:

    标签: php mysql time intervals


    【解决方案1】:

    你可以用php timestamp试试这个

    $reference_start_date = "1.1.2014";
    $reference_end_date = "1.2.2014";
    
    $comparative_start_date = "1.4.2014";
    $comparative_end_date = "1.5.2014 ";
    
    $reference_start_time = strtotime(str_replace(".", "-", $reference_start_date);
    $reference_end_time = strtotime(str_replace(".", "-", $reference_end_date);
    
    $comparative_start_time = strtotime(str_replace(".", "-", $comparative_start_date);
    $comparative_end_time = strtotime(str_replace(".", "-", $comparative_end_date);
    
    if($comparative_start_time>$reference_start_time && $comparative_start_time<$reference_end_time)
    {
        echo "Not OK";
    }
    else if($comparative_end_time>$reference_start_time && $comparative_end_time<$reference_end_time)
    {
        echo "Not OK";
    }
    else if($comparative_start_time<$reference_start_time && $comparative_end_time>$reference_end_time)
    {
         echo "Not OK";
    }
    else
    {
         echo "OK";
    }
    

    【讨论】:

    • 试过了,似乎效果很好。比我的 if-else-mess 更好。谢谢!
    【解决方案2】:

    你可以这样做:

    检查Reference_start &gt;= comparative_start &amp;&amp; Reference_end &lt; comparative_end,如果此条件成立,您的时间将重叠。

    【讨论】:

      【解决方案3】:

      如果你有一个reference 句点(有startDateendDate)并且你有一个comparative 句点,那么你可以在MySQL 中有这个where 子句:

      where ((reference.startDate > comparative.endDate) or reference.endDate < comparative.startDate)
      

      如果两个时期没有交集,则为真。

      【讨论】:

        【解决方案4】:

        假设您的日期是 UTC,那么比较两个日期范围非常简单。可能会发生 5 种特定情况:

        11111......
        ......22222
        
        ..11111.....
        .....22222..
        
        ...11111....
        ...22222....
        
        .....11111..
        ..22222.....
        
        ......11111
        22222......
        

        只有第一个和最后一个是您要查找的。很容易构造一个 if 查询并否定它:

        if (!($dateRange1End <= $dateRangeStart2 && $dateRange2End <= $dateRange1Start))
            // NOT OKAY
        else
            // OKAY
        

        【讨论】:

          猜你喜欢
          • 2020-06-22
          • 2011-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多