我正在使用PHP和MySQL,并且想要计算两个日期时间之间的时间差。我有一个消息表,在该表中,createdate
是一个字段。我想以1天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");
SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;
然后在php端,您可以轻松将diff_in_hours
的值转换为天数+小时格式。
HH:MM:ss.s
的格式给出了毫秒级别的时间差。 - Osh MansorTIMESTAMPDIFF
的第一个参数也可以是 MINUTE
、SECOND
或 MICROSECOND
(http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff)。在你的问题中,你询问了关于天数和小时数的问题,所以我在我的示例代码中使用了 HOUR
单位。 - a1ex07在MySQL中,您可以使用DATEDIFF()
和TIMEDIFF()
函数。
SELECT DATEDIFF(CURDATE(), createdate) AS output_day,
TIMEDIFF(CURDATE(), createdate) AS output_time
FROM message_table
对于output_day,它已经在天单位中了。但是,output_time需要进行额外的操作以获得时间差的小时部分。
希望这可以帮助到您。