【问题标题】:Calculate difference between two datetimes计算两个日期时间之间的差异
【发布时间】:2011-08-01 22:53:54
【问题描述】:

我正在使用 PHP 和 MySQL,并且想计算两个日期时间之间的日期时间差。我有一个消息表,在该表中createdate 是一个字段。我想以1 day 2 hours ago 的格式找出与当前日期的日期和时间差。解决此问题的最佳方法是什么?

【问题讨论】:

    标签: php mysql datetime


    【解决方案1】:
    SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;
    

    然后在 php 端,您可以轻松地将 diff_in_hours 的值转换为天 + 小时格式。

    【讨论】:

    • @Sanjay:我写的解决方案以以下格式给出了高达几分之一秒的时间差HH:MM:ss.s
    • @Sanjay:TIMESTAMPDIFF 的第一个参数也可以是MINUTE,或SECOND,或MICROSECONDdev.mysql.com/doc/refman/5.5/en/…)。在您的问题中,您询问了天+小时,因此我将HOUR 单位放入我的示例代码中。
    【解决方案2】:

    使用 PHP 的内置日期函数:

    <?php
        $start_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
        $end_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
    
        // both of the above formats are the same as what MySQL stores its
        // DATETIMEs in
    
        $start = new DateTime($start_time);
        $interval = $start->diff(new DateTime($end_time));
    
        echo $interval->format("d \d\a\y\s h \h\o\u\r\s");
    

    【讨论】:

    【解决方案3】:

    您可以在 MySQL 中使用 DATEDIFF()TIMEDIFF() 函数。

    SELECT DATEDIFF(CURDATE(), createdate) AS output_day, 
    TIMEDIFF(CURDATE(), createdate) AS output_time 
    FROM message_table
    

    对于 output_day,它已经以天为单位。但是 output_time 需要额外的操作来获得时差的小时部分。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多