我正在使用PHP和MySQL,并希望计算两个日期时间之间的日期时间差。我有一个消息表,该表createdate
是一个字段。我想以格式1 day 2 hours ago
找出当前日期的日期和时间差异。最好的方法是什么?
答案 0 :(得分: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");
答案 1 :(得分:4)
SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;
然后在php端,您可以轻松地将diff_in_hours
的值转换为天+小时格式。
答案 2 :(得分:1)
您可以在MySQL中使用DATEDIFF()
和TIMEDIFF()
函数。
SELECT DATEDIFF(CURDATE(), createdate) AS output_day,
TIMEDIFF(CURDATE(), createdate) AS output_time
FROM message_table
对于output_day,它已经是日期单位。但是output_time需要额外的操作来获得时差的小时部分。
希望这有帮助。