查找时间是否在定义的范围内

时间:2012-04-26 09:43:30

标签: php

  

可能重复:
  How to check if a date is in a given range?
  How to check if date(entered by user) is in given range (Date format :-day month ie.:-1 june )

我试图找出日期是否在定义的范围内。我正在使用以下代码:

    $apple='25 March';
    $udate= date('d F',strtotime($apple));

    echo $udate;
    $startDate='21 March';
    $realStartDate= date('d F',strtotime($startDate)) ;
    echo $realStartDate;
    $endDate='19 April';
    $realEndDate= date('d F',strtotime($endDate)) ;
    if ($udate >= $realStartDate && $udate <= $realEndDate ) {
        echo 'within tange';
    }
    else{
        echo 'Not in range';
    }
    ?>

我哪里错了?

5 个答案:

答案 0 :(得分:2)

尝试这个工作......

<?php
        $udate          = '25 March';
        $udateTimestamp = strtotime($udate);


        $startDate          = '21 March';
        $startDateTimestamp = strtotime($startDate);

        $endDate           = '19 April';
        $eEndDateTimestamp = strtotime($endDate);

        if ($udateTimestamp >= $startDateTimestamp && $udateTimestamp <= $eEndDateTimestamp)
        {
                echo 'within tange';
        }
        else
        {
                echo 'Not in range';
        }
?>

答案 1 :(得分:1)

比较时间戳而不是字符串表示!

if(strtotime($apple) < strtotime($endDate) && strtotime($apple) > strtotime($startDate)){
 // All ok!
}

答案 2 :(得分:0)

喜欢这个

if(strtotime($givendate) > strtotime('3/21/xxxx') && strtotime($givendata) < strtotime('4/19/xxxx')) {
   // Its within range
}

答案 3 :(得分:0)

您可以使用DateTime

$userDate = new DateTime("2012-03-01");

if ( $userDate > new DateTime("2012-03-21 00:00:00") &&  $userDate < new DateTime("2012-04-19 23:59:59"))
{
   // In Range 
}

如果格式为(7月1日)

,请将其置于函数中
if (inRange ( "1 June", "3 March", "7 December" )) {
    echo "In Range";
} else {
    echo "Out Of Range";
}

function inRange($dateCheck, $dateFrom, $dateTo) {

    $date = DateTime::createFromFormat ( "d F", $dateCheck );
    $date1 = DateTime::createFromFormat ( "d F", $dateFrom );
    $date2 = DateTime::createFromFormat ( "d F", $dateTo );

    if ($date > $date1 && $date < $date2) {
        return true;
    }

    return false;

}

答案 4 :(得分:0)

试试这个

 if (strtotime($udate) >= strtotime($realStartDate) && strtotime($udate) <= strtotime($realEndDate) ) {
    echo 'within tange';
}
else{
    echo 'Not in range';
}