【发布时间】:2011-08-23 16:44:58
【问题描述】:
我在 MySQL Server 5.1 中创建了一个存储过程。
如何将时间戳转换为表示该时间戳与现在之间的天、小时和分钟差异的字符串?
例如,如果时间戳是 5 小时 3 分钟前,我将得到“5 小时 3 分钟前”。
【问题讨论】:
我在 MySQL Server 5.1 中创建了一个存储过程。
如何将时间戳转换为表示该时间戳与现在之间的天、小时和分钟差异的字符串?
例如,如果时间戳是 5 小时 3 分钟前,我将得到“5 小时 3 分钟前”。
【问题讨论】:
select date_format(timediff(current_timestamp,last_timestamp),
'%k hours, %i minutes, %s seconds ago');
如果你想要更多的奢华,你可以这样做:
select concat
(
if(date_format(timediff(ts1,ts2)'%k')='0'
,'',date_format(timediff(ts1,ts2)'%k hours'),
if(date_format(timediff(ts1,ts2)'%i')='0'
,'',date_format(timediff(ts1,ts2)'%k minutes'),
if(date_format(timediff(ts1,ts2)'%s')='0'
,'',date_format(timediff(ts1,ts2)'%k seconds')
)
这里和那里还有一些额外的空格。
如果其中一个时间戳是null,那么结果自然也会为空,您必须确保它不是,或者使用ifnull(`timestamp`,now()) 来解决这个问题。
见:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff
【讨论】:
TIMEDIFF 函数将 only return a maximum of 838:59:59。更多信息见this article。
查看 MySQL 参考页面以了解日期和时间函数
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
编辑:因为我假设您使用的是 Unix 时间戳,所以要走的路是
FROM_UNIXTIME(timestamp, format)
【讨论】: