PHP日期范围检查

时间:2011-06-20 13:22:11

标签: php

我有2个日期范围

[contract_start_date] => 2011-10-20 [contract_end_date] => 2011-10-29

我想验证以下日期是否在

以上的日期范围内
 2011-05-05 and 2011-10-10

所给出的日期不得以任何方式超出合同范围

PHP中是否有这个功能?

4 个答案:

答案 0 :(得分:9)

请参阅:: http://php.net/manual/en/datetime.diff.php

$datetime1 = new DateTime('2011-10-20');
$datetime2 = new DateTime('2011-10-29');

//PHP 5.3.0
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

//PHP 5.2.2
var_dump($datetime1 < $datetime2);

$datetime3 = new DateTime('2011-05-05');
$datetime4 = new DateTime('2011-10-10');

if ($datetime3 > $datetime1 && $datetime2 > $datetime1 && $datetime3 < $datetime2 && $datetime2 < $datetime2) {
    //valid range
}//end if

答案 1 :(得分:2)

$start = strtorime($contract_start_date);
$end = strtotime($contract_end_date);

$required_start = strtotime("2011-05-05");
$required_end = strtotime("2011-10-10");

if ($end > $required_end or $end < $required_start)
{
  //out of range
}

if ($start < $required_start or $start > $required_end)
{
  //out of range
}

答案 2 :(得分:1)

这应该可以满足您的需求:

 define(CONTRACT_START, "2011-10-20");
 define(CONTRACT_END, "2011-10-29");

 function checkDateRange($dateArray)
 {
    foreach($dateArray as $dateStr)
    {
        $curDate = strtotime($dateStr);
        if($curDate < strtotime(CONTRACT_START) || $curDate > strtotime(CONTRACT_END))
        {
            return false;
        }   
    }   
    return true;
 }   


$dates = array( 0 => "2011-10-02", 1 => "2011-10-25");

if(checkDateRange($dates))
{
    echo "Dates are within range";
}   
else
{
    echo "Dates are NOT within range";
}   

答案 3 :(得分:1)

查找以下代码以获取日,月和年的日期差异:

<?php
function datediff($date1,$date2,$format='d'){
    $difference = abs(strtotime($date2) - strtotime($date1));
    switch (strtolower($format)){
    case 'd':
        $days = round((($difference/60)/60)/24,0);
        break;
    case 'm':
        $days = round(((($difference/60)/60)/24)/30,0);
        break;
    case 'y':
        $days = round(((($difference/60)/60)/24)/365,0);
        break;
    }
    return $days;
}
//Example
echo datediff('2011-06-1','2010-8-30','D') . ' Days<br />'; 
echo datediff('2011-06-1','2010-8-30','m') . ' Months<br />'; 
echo datediff('2011-06-1','2010-8-30','y') . ' Years<br />';
?>