我有两个字符串格式如下:
$status = "15:00";
$time = "15:00";
我想简单地使用 php 比较它们:
if($status == $time)
{
echo 'true';
}
else
{
echo '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(),这会将字符串日期转换为整数,然后很容易比较。