我有一个带有以下属性的mysql列
listDate TIMESTAMP DEFAULT = CURRENT_TIME
我正在我的表格中显示它
echo "<td>" . $row['listDate'] . "</td>";
如何将输出转换为自发布以来的时间而不是默认值:
2014-12-17 00:32:50
答案 0 :(得分:1)
使用DateTime类
$timePosted = new DateTime ($row['listdate']);
$timeNow = new DateTime("now");
$timeSince = $timePosted->diff($timeNow);
echo $timeSince->format("Since posted passed %a days, %h hours, %i minutes and %s seconds");
答案 1 :(得分:1)
在MySQL查询中,您可以使用TimeStampDiff
SELECT
timestampdiff(MINUTE,listDate, NOW()) as minutes_from_list_date
FROM table_name
如果您阅读文档,您应该了解如何将输出更改为您可能需要/需要的方法。
在你的php代码中使用它,你会这样称呼它:
echo '<td>'. $row['minutes_from_list_date'] . '</td>';
答案 2 :(得分:1)
Mysql有一个函数 timestampdiff() ,您可以使用它来生成类似下面的查询,并将其广泛用于评论/回复部分,其中显示为
1 year ago
,10 days ago
,2 hours ago
,just now
等
select
case
when timestampdiff(year,'2014-12-17 10:10:24',now()) > 0 then concat(timestampdiff(year,'2014-12-17 10:10:24',now()) ,' years ago')
when timestampdiff(month,'2014-12-17 10:10:24',now()) > 0 then concat(timestampdiff(month,'2014-12-17 10:10:24',now()) ,' months ago')
when timestampdiff(day,'2014-12-17 10:10:24',now()) > 0 then concat(timestampdiff(day,'2014-12-17 10:10:24',now()) ,' days ago')
when timestampdiff(hour,'2014-12-17 10:10:24',now()) > 0 then concat(timestampdiff(hour,'2014-12-17 10:10:24',now()) ,' hours ago')
when timestampdiff(minute,'2014-12-17 10:10:24',now()) > 0 then concat(timestampdiff(minute,'2014-12-17 10:10:24',now()),' minutes ago')
else 'just now'
end as posted ;
+-------------+
| posted |
+-------------+
| 3 hours ago |
+-------------+
在查询中,您可以使用列名更改硬编码的日期时间值。
逻辑是
首先会检查年份的差异是否大于0,然后设置字符串posted {diff in years} ago
如果是几个月,则设置
如果是天,则设置
如果是几小时,则设置
如果是分钟,则设置
将字符串设置为刚刚