PHP时间比较错误的回声

时间:2015-04-14 12:27:30

标签: php datetime

$first = date("h:iA", strtotime('20:00'));
$second = new DateTime('6:00PM');

if ( $first > $second ) {
  echo 'Correct';
}
else {
  echo 'Wrong';
}

这是我目前的代码并且是错误的回应。晚上8点大于下午6点对吗?我的代码有问题吗?

4 个答案:

答案 0 :(得分:4)

仅使用strtotime执行此操作。

$first  = strtotime('20:00');
$second = strtotime('6:00PM');

if ( $first > $second ) {
  echo 'Correct';
}
else {
  echo 'Wrong';
}

希望这能解决问题。

答案 1 :(得分:3)

坚持使用一种类型的USE strtotimeDateTime类进行数据/时间相关的操作。

$first  = strtotime('20:00');
$second = strtotime('6:00PM');
var_dump($first > $second);

OR

$first = new DateTime("20:00");
$second = new DateTime("6:00PM");
var_dump($first > $second);

答案 2 :(得分:0)

是的。就像Marmar之前所说的那样,您正在将StringDateTime对象进行比较。

我刚刚重新创建了代码,这是一个转储结果:

string '08:00PM' (length=7)

object(DateTime)[1]
  public 'date' => string '2015-04-14 18:00:00' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Paris' (length=12)

答案 3 :(得分:-1)

将DateTime转换为String,它可以正常工作。

$first = date("h:iA", strtotime('20:00'));
$date = new DateTime('6:00PM');
$second = $date->format('h:iA');
if ( $first > $second ) {
  echo 'Correct';
}
else {
  echo 'Wrong';
}