如何检查从日期到日期之间的两个日期

时间:2013-04-04 06:19:17

标签: php datetime

我有两个约会from-date& to-date

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

实施例: 我必须查看这些日期: - > from = 15 March 2013& 15 April 2013在以下日期之间是否有任何天数介于这两个日期之间。

来自db table

的数据
 #       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

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

2 个答案:

答案 0 :(得分:3)

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

因为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

要真正回答你的问题:

您需要测试重叠的两个范围,此问题已在此处回答What's the most efficient way to test two integer ranges for overlap?

// our two ranges overlap if the following conditions are met
$dateRangeOverlaps = $referenceFromTimestamp <= $toTimestamp and $fromTimestamp <= $referenceToTimestamp;

答案 1 :(得分:-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";
    }