繁体   English   中英

如何从数据库中的日期时间中减去当前日期时间-PHP

[英]How to Subtract current date time from date time in database - PHP

我正在做一个项目。我必须检查“多少分钟前,用户更新了数据库”。为此,我使用了以下代码:

 <?php include('connect_db.php'); $sql =" SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $time = strtotime($row['time_']); $current=time(); $sub_time=$current-$time; echo $sub_time; } 

问题在于代码正在返回负值,例如[-17173]。 存储在我的数据库中的日期时间就像[2018-07-14 11:42:21.006515]

我只是想将当前时间与数据库中存储的时间进行比较,以秒或分钟为单位。 我需要帮助来解决这个问题。谢谢。

您可以更改select语句,以秒为单位提供时差,如下所示:

$sql  =" select UNIX_TIMESTAMP(current_Timestamp()) - UNIX_TIMESTAMP(time_) FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ; 

您首先需要将它们转换为时间戳。 然后减去它们,将重新开始的时间戳转换回所需的格式。

    while($row = $result->fetch_assoc()) {  

       $time = strtotime($row['time_']);

       $current=time();
       $sub_time=date('d-m-y h:i:s',(strototime(date('d-m-y h:i:s')-$time));
       echo $sub_time;
}

您还需要处理大于和小于的情况。

我认为DateTime是更好的方法,因为它具有实现所需结果的方法。

也许是这样的:

$time=$row['time_'];
$curr_time=new DateTime();
$difference=$time->diff($curr_time);

http://php.net/manual/en/class.datetime.php

更新

您应该使用DateTime函数找出时间差。 您应该能够将此集成到您的代码中。

我将建议的代码作为函数合并到您的原始代码中。 这应该为您工作。

尝试这个:

function timeDiff($date){

  $date     = new DateTime(date('Y-m-d H:i:s', strtotime($date)));
  $current  = new DateTime(date('Y-m-d H:i:s'));
  $interval = $date->diff($current);
  return $interval->format('%H:%I:%S');


}

include('connect_db.php');

$sql  ="SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;    

$result = $conn->query($sql);

  if ($result->num_rows > 0) {


      while($row = $result->fetch_assoc()) {  

         echo timeDiff($row['time_']);
  }

}

暂无
暂无

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

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