【发布时间】:2011-08-01 22:53:54
【问题描述】:
我正在使用 PHP 和 MySQL,并且想计算两个日期时间之间的日期时间差。我有一个消息表,在该表中createdate 是一个字段。我想以1 day 2 hours ago 的格式找出与当前日期的日期和时间差。解决此问题的最佳方法是什么?
【问题讨论】:
我正在使用 PHP 和 MySQL,并且想计算两个日期时间之间的日期时间差。我有一个消息表,在该表中createdate 是一个字段。我想以1 day 2 hours ago 的格式找出与当前日期的日期和时间差。解决此问题的最佳方法是什么?
【问题讨论】:
SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;
然后在 php 端,您可以轻松地将 diff_in_hours 的值转换为天 + 小时格式。
【讨论】:
HH:MM:ss.s
TIMESTAMPDIFF 的第一个参数也可以是MINUTE,或SECOND,或MICROSECOND(dev.mysql.com/doc/refman/5.5/en/…)。在您的问题中,您询问了天+小时,因此我将HOUR 单位放入我的示例代码中。
使用 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");
【讨论】:
您可以在 MySQL 中使用 DATEDIFF() 和 TIMEDIFF() 函数。
SELECT DATEDIFF(CURDATE(), createdate) AS output_day,
TIMEDIFF(CURDATE(), createdate) AS output_time
FROM message_table
对于 output_day,它已经以天为单位。但是 output_time 需要额外的操作来获得时差的小时部分。
希望这会有所帮助。
【讨论】: