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

时间:2018-07-14 08:04:26

标签: php mysql

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

<?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]

我只是想将当前时间与数据库中获取结果的时间进行比较(以秒或分钟为单位)。 我需要帮助解决此问题。谢谢。

4 个答案:

答案 0 :(得分:2)

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

int(...)

答案 1 :(得分:0)

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

    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;
}

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

答案 2 :(得分:0)

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

也许是这样的:

unsigned long long

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

答案 3 :(得分:0)

已更新

您应该使用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_']);
  }

}
相关问题