繁体   English   中英

PHP - 比较日期,检查是否在过去一小时内

[英]PHP - Comparing date, checking if within last hour

我正在尝试查看时间是否在最后一小时内。

$unit_date = date($unit['last_accessed'], 'Y-m-d H:i:s');

$last_hour = date('Y-m-d H:i:s', strtotime('-1 hour')); 

if($unit_date >= $last_hour ){
    $connect = "<i class='fa fa-circle 2x' style='color:#2ECC71;'></i>";
} else {
    $connect = '';
}

如您所见,我将 $unit['last_accessed'] 放入正确的格式,然后与一小时前进行比较。 如果时间在最后一小时内 $connect 是一个字体很棒的圆圈(绿色),如果不是在最后一小时内它是空的,现在它说在最后一小时内什么都没有,这是错误的。

if(time() - strtotime($unit['last_accessed']) < 3601){

要么

if(time() - strtotime($unit['last_accessed']) > 3599){

time()和strtotime()都以秒为单位使用相同的时基

如果$ unit ['last_accessed']已经是整数时间变量,那么不要使用strtotime()。

首先,您正在以错误的方式使用日期功能。 从PHP的手册:

date ( string $format [, int $timestamp = time() ] )

您必须提供$ format字符串作为第一个参数,并将$ timestamp作为第二个参数。 您可以检查时间是否在最后一小时,而不将Unix时间戳转换为另一个时间戳字符串。

$last_hour = time() - 60*60; //last hour timestamp
if($unit['last_accessed'] >= $last_hour){
       $connect = "<i class='fa fa-circle 2x' style='color:#2ECC71;'></i>";
}else{
       $connect = '';
}

正如你所看到的,我没有对时间戳进行任何转换,因为我没有在任何地方使用时间轴。 您应该了解有关使用unix时间戳或php时间函数的操作的更多信息。

参考文献: http //php.net/manual/en/function.date.php

日期时间解决方案

$firstDate = new \DateTime('2019-10-16 07:00:00');
$secondDate = new \DateTime('2019-10-17 07:00:00');

$diff = $firstDate->diff($secondDate);
$diffHours = $diff->h;

// diff in hours (don't worry about different years, it's taken into account)
$diffInHours = $diffHours + ($diff->days * 24);

// more than 1 hour diff
var_dump($diffInHours >= 1);

来源类似的答案: Calculate number of hours between 2 dates in PHP

你的代码中有错误。 在一个地方,你date这样称呼date

日期( 格式时间

在另一个地方,像这样:

日期( 时间格式

检查PHP文档的date ,找出哪一个是正确的。 否则,您的代码看起来在逻辑上是正确的,如果可能不必要的复杂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM