【问题标题】:PHP comparing time values [closed]PHP比较时间值[关闭]
【发布时间】:2013-10-08 09:45:23
【问题描述】:

我有两个字符串格式如下:

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

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

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

即使之前的值相同(作为字符串),我也会得到错误的值。 我想知道是否有办法将它们的类型更改为“时间”并进行比较??

【问题讨论】:

  • 此代码为所有 php 版本返回 true,see。

标签: php string time


【解决方案1】:

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

$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';

【讨论】:

  • 这与 OP 所写的字符串比较相同。无需初始化额外的对象。但是,如果他将使用其他比较运算符,这是一个很好的解决方案。
  • 是的,我同意,这是一个不好的例子。但我喜欢那些 DateTime 对象,因为它们给了我很大的灵活性,比如设置时区等等。
  • 我知道,DateTimerockz ;-)
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      相关资源
      最近更新 更多