PHP Compare two date and time [duplicate]

2020-07-27 03:50发布

I have three dates A, B and C.

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

What I am trying to do is check if C is inside A and B, if it is return true. Anyone have any idea of how to do this?

I tried this with no luck

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

标签: php date
4条回答
SAY GOODBYE
2楼-- · 2020-07-27 04:28

Use the strtotime function.

    $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.";
    }
查看更多
Viruses.
3楼-- · 2020-07-27 04:29

You can convert them to UNIX timestamp to compare.

$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'";
 }
查看更多
冷血范
4楼-- · 2020-07-27 04:37

Use the DateTime class:

$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";
}
查看更多
闹够了就滚
5楼-- · 2020-07-27 04:41

use the following code to compare date value in 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;
               }
            ?>
查看更多
登录 后发表回答