PHP比较两个日期和时间

时间:2013-08-13 12:48:30

标签: php date

我有三个日期A,B和C.

A = 2013-08-10 10:00
B = 2013-08-10 12:00
C = 2013-08-10 10:22

我要做的是检查C是否在A和B内,如果它返回true。任何人都知道如何做到这一点?

我试了这个没有运气

    if ($time >= $date_start && $time <= $date_end)
    {
        echo "is between\n";
    } else {
        echo 'no';
    }

4 个答案:

答案 0 :(得分:7)

您可以将它们转换为UNIX时间戳进行比较。

$A = strtotime($A); //gives value in Unix Timestamp (seconds since 1970)
$B = strtotime($B);
$C = strtotime($C);

if ((($C < $A) && ($C > $B)) || (($C > $A) && ($C < $B)) ){
  echo "Yes '$C' is between '$A' and '$B'";
 }

答案 1 :(得分:3)

使用strtotime功能。

    $A = "2013-08-10 10:00";
    $B = "2013-08-10 12:00";
    $C = "2013-08-10 10:22";

    if (strtotime($C) > strtotime($A) && strtotime($C) < strtotime($B)){
    echo "The time is between time A and B.";
    }else{
    echo "It is not between time A and B.";
    }

答案 2 :(得分:3)

使用以下代码比较php中的日期值

                 <?php
               $a = new DateTime("2013-08-10 10:00");

               $b= new DateTime("2013-08-10 12:00");

                  $c = new DateTime('2013-08-10 10:22');
               if(($a<$c)&&($c<$b))
               {
               return true;
               }
            ?>

答案 3 :(得分:-1)

使用DateTime类:

$A = '2013-08-10 10:00';
$B = '2013-08-10 12:00';
$C = '2013-08-10 10:22';

$dateA = DateTime::createFromFormat('Y-m-d H:m', $A);
$dateB = DateTime::createFromFormat('Y-m-d H:m', $B);
$dateC = DateTime::createFromFormat('Y-m-d H:m', $C);

if ($dateA >= $dateB && $dateA <= $dateC)
{
  echo "$dateA is between $dateB and $dateC";
}