I've created a stored procedure in MySQL Server 5.1.
How can I convert a timestamp to a string that represents the da开发者_如何学Pythonys, hours, and minutes difference between that timestamp and now?
For example, if the timestamp is 5 hours and 3 minutes ago I'll get '5 hours 3 minutes ago'.
select date_format(timediff(current_timestamp,last_timestamp),
'%k hours, %i minutes, %s seconds ago');
If you want more luxury you can do something like:
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')
)
Plus a few extra spaces here and there.
If one of the timestamps is null
naturally the result will also be null, you'll have to make sure it is not, or use ifnull(`timestamp`,now())
to fix that.
See: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff
Have a look at the MySQL reference page for date and time functions at
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
Edit: Since I assume you are using Unix timestamps, the way to go is
FROM_UNIXTIME(timestamp, format)
精彩评论