计算两个日期时间之间的差异

8

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

3个回答

6

使用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");

注:以上链接是关于 PHP 中与日期和时间相关的两个类的文档。

那 PHP 5.2 及以下的呢? - Vipul Hadiya

4
SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;

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


@Sanjay:我写的解决方案以HH:MM:ss.s的格式给出了毫秒级别的时间差。 - Osh Mansor
@Sanjay:TIMESTAMPDIFF 的第一个参数也可以是 MINUTESECONDMICROSECOND(http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff)。在你的问题中,你询问了关于天数和小时数的问题,所以我在我的示例代码中使用了 HOUR 单位。 - a1ex07

1

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

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

对于output_day,它已经在天单位中了。但是,output_time需要进行额外的操作以获得时间差的小时部分。

希望这可以帮助到您。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接