检查Timetstamp是否超过1小时不工作?

时间:2015-10-16 08:22:50

标签: php

不确定为什么但这个if语句不起作用。我在这做错了什么?

$timestamp = $order->datetime;
if ($timestamp >= strtotime("-1 hour")) {
    echo "PULL FROM DB!";
} else {
    echo "PULL FROM API";
}

由于

2 个答案:

答案 0 :(得分:1)

您正在尝试将日期字符串与时间戳进行比较。您在if语句中实际比较的内容如下:

if("2015-10-16 08:21:11" >= 1444987642){
 echo "PULL FROM DB!";
} else {
 echo "PULL FROM API";
}

这不是你想要的。在比较之前,您需要将日期字符串转换为时间戳。试试这个:

$dateString = $order->datetime;
$timestamp = strtotime($dateString);

if ($timestamp >= strtotime("-1 hour")) {
    echo "PULL FROM DB!";
} else {
    echo "PULL FROM API";
}

关键部分是您将日期字符串转换为时间戳:

$timestamp = strtotime($dateString);

答案 1 :(得分:0)

我试过

$timestamp = strtotime("now");
if ($timestamp >= strtotime("-1 hour")) {
    echo "PULL FROM DB!";
} else {
    echo "PULL FROM API";
}

结果:从数据库中拉出来! 和

$timestamp = strtotime("now");
if ($timestamp >= strtotime("1 hour")) {
    echo "PULL FROM DB!";
} else {
    echo "PULL FROM API";
}

结果:从API中提取

请检查您传递的值

$timestamp = $order->datetime;