如果现在的时间自上次更新以来超过 3 小时


If time now is more than 3 hours since last update

我需要有一个验证来检查"last_update"是否在 3 小时或更短的时间内完成。

我有这个PHP代码:

if($user['last_update'] < strtotime("3 hours")) {
    $msg .= "You can only register every 3 hour.";
}

怎么能做到这一点呢?

如果$user['last_update']是日期格式,则

if (time() - strtotime($user['last_update']) < 3 * 3600) {
  //..
}

试试这样。把你的$user['last_update']包裹在strtotime()里面。

if(strtotime($user['last_update']) < strtotime("3 hours")) {
    $msg .= "You can only register every 3 hour.";
}

您可以使用它来获取当前时间减去 3 小时:

$dateTime = new DateTime();
$dateTime->modify("-3 hours");
$time = $dateTime->format("H:m:s");
$date = $dateTime->format("Y-m-d");

然后,您可以将日期和时间变量与上次更新进行比较。

strtotime()

返回秒。

如果您的日期存储为 UNIX 时间戳,则您的代码是正确的。如果您的日期存储为 TIMESTAMP,则代码如下:

$three_hours = date('Y-m-d H:i:s', strtotime('3 hours'));
if ($user['last_update'] < $three_hours) {
    $msg .= "You can only register every 3 hour.";
}