0

我有两个日期from-date& to-date

我必须从下面显示的现有日期对它们进行比较,是否有任何一天在它们之间或不使用 php?
我可以做单日期检查,但我对两个日期检查感到困惑。

示例:我必须检查这些日期:-> from= 15 March 2013 &15 April 2013 在以下日期之间,无论是否有任何日子在这两个日期之间。

以下来自 db 表的数据

 #       from date            to-date
-----------------------------------------
1     01 April 2013         30 April 2013   //here we will find as falling
2     01 May 2013           15 May 2013   
3     01 June 2013          20 June 2013

目前,在我看来,甚至没有一个逻辑可以尝试。请给我有关此问题的任何逻辑或建议..

4

2 回答 2

3

比较日期的最简单方法是将它们转换为unix 时间戳

因为 unix 时间戳是一个整数,所以您可以简单地使用关系运算符来比较它们。

例子

// set some example data
$referenceDate = '01 April 2013';
$fromDate = '01 January 2013';
$toDate = '01 June 2013';

// convert dates to timestamps (strings to integers)
$referenceTimestamp = strtotime( $referenceDate );
$fromTimestamp = strtotime( $fromDate );
$toTimestamp = strtotime( $toDate );

// isBetween is Boolean TRUE if reference date is greater or equal fromDate and smaller or equal toDate
$isBetween = $referenceTimestamp >= $fromTimestamp and $referenceTimestamp <= $toTimestamp;

编辑 1

要实际回答您的问题:

你有两个范围需要测试重叠,这个问题已经在这里得到了回答什么是测试两个整数范围重叠的最有效方法是什么?

// our two ranges overlap if the following conditions are met
$dateRangeOverlaps = $referenceFromTimestamp <= $toTimestamp and $fromTimestamp <= $referenceToTimestamp;
于 2013-04-04T06:41:58.427 回答
-1

请尝试代码,

    $ourdate = strtotime('1 April 2013'); // Your date which is to be checked

    $from = strtotime('15 March 2013'); // From date
    $to = strtotime('15 April 2013'); // To date

    if ($ourdate >= $from && $ourdate <= $to)
    {
      echo "Date falls";
    }
    else
    {
    echo "No Date falls";
    }

如果您需要检查多个日期,请将其作为数组传递,如下所示...

   $i=0;
   $dates= array("11 April 2013","16 April 2013");
   foreach($dates as $ourdates)
   {
    $ourdate= strtotime($ourdates); //Your dates to be checked
    $from = strtotime('15 March 2013'); // From date
    $to = strtotime('15 April 2013'); // To date

          if ($ourdate >= $from && $ourdate <= $to)
              {
                 $i++;
              }
    }
    if($i>0)
    {
    echo "Date falls";
    }
    else
    {
    echo "No Date falls";
    }
于 2013-04-04T06:35:09.900 回答