PHP 比较时间值


PHP comparing time values

>我有如下格式的拖曳字符串:

$status = "15:00";
$time = "15:00";

我想简单地使用 php 比较它们:

if($status == $time)
{
echo 'true';
} 
else
{
echo 'false';
}

对于以前的值,即使它们是相同的(作为字符串(,我也得到 false。我想知道是否有办法将它们的类型更改为"时间"并进行比较?

您应该比较时间戳或 DateTime 对象而不是字符串:

$status = new DateTime( '15:00' );
$time   = new DateTime( '15:00' );
echo $status == $time ? 'yes' : 'no';

更新;基于评论:

/* you can also check, which timestamps was earlier or later */
echo $status > $time ? '$status is later then $time' : '$time is later then $status';

使用 strtotime() 进行时间比较。在此处查看手册

$status = "15:01";
$time = "15:00";
if(strtotime($status) == strtotime($time))
{
echo 'true';
} 
else
{
echo 'false';
}

使用 strtotime((,这会将字符串日期转换为整数,然后很容易比较。

http://www.php.net/manual/en/function.strtotime.php