【问题标题】:How to Subtract current date time from date time in database - PHP如何从数据库中的日期时间减去当前日期时间 - PHP
【发布时间】:2018-07-14 08:04:25
【问题描述】:

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

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

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

【问题讨论】:

  • 您的代码看起来不错,但我不确定strtotime() 能否理解您的日期时间格式。 PHP 手册不是很有帮助:php.net/manual/en/datetime.formats.compound.php 我在那里看不到你的。为什么不剪掉最后一点,使用 MySQL 格式呢?所以你只剩下这一点:2018-07-14 11:42:21.
  • time() 函数以 UTC 格式返回日期。如果您的数据库时间是本地时间,请改用 date()。

标签: php mysql


【解决方案1】:

您只需更改您的选择语句,即可为您提供以秒为单位的时差,如下所示:

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

【讨论】:

    【解决方案2】:

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

    可能是这样的:

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

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

    【讨论】:

      【解决方案3】:

      更新

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

      【讨论】:

        【解决方案4】:

        您首先需要将它们转换为时间戳。然后他们减去他们将结果时间戳转换回你想要的格式。

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

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

        【讨论】:

          猜你喜欢
          • 2023-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多