A few months back I was creating a web application where I needed to display a time span similar to “4 secs ago”. I was using PHP to create the application. I was running into a lot of errors with cache sizes and memory usage. I had to find another way to complete this task. I was trying to sort the query using PHP scripts, but this was causing more problems than solutions. I had to find a different way of completing these tasks.
Problem: I had to take timestamps similar to 2011-10-05 08:09:00.000 and display them as “4 secs ago”.
I started to do some research and remembered that MySQL can store functions. I then went to work creating a function for my MySQL queries and then ran through the table. The function had to take the timestamp 2011-10-05 08:09:00.000 as an input and then take the current time and convert it to a human readable format similar to “4 secs ago”. I tried to use MySQL functions like timediff() and format(), but with no luck.
I ended up with a function similar to the one below.
DELIMITER $$
DROP FUNCTION IF EXISTS `GetTimeDisplay` $$
CREATE FUNCTION `GetTimeDisplay` (GivenTimestamp TIMESTAMP)
RETURNS VARCHAR(32)
DETERMINISTIC
BEGIN
DECLARE rv VARCHAR(32);
DECLARE diff BIGINT;
SET diff = UNIX_TIMESTAMP()-UNIX_TIMESTAMP(GivenTimestamp);
IF diff < 0 THEN
SET rv = CONCAT(abs(diff/60),' From Now');
END IF;
IF diff = 0 THEN
SET rv = 'Just Now';
END IF;
IF diff = 1 THEN
SET rv = '1 sec ago';
END IF;
IF diff BETWEEN 2 AND 60 THEN
SET rv = CONCAT(FORMAT(diff, 0), ' secs ago');
END IF;
IF diff BETWEEN 120 AND 3599 THEN
SET rv = CONCAT(FORMAT(diff/60, 0), ' mins ago');
END IF;
IF diff BETWEEN 61 AND 119 THEN
SET rv = CONCAT(FORMAT(diff/60, 0), ' min ago');
END IF;
IF diff = 3600 THEN
SET rv = CONCAT(FORMAT(diff/3600, 0), ' hr ago');
END IF;
IF diff BETWEEN 3601 AND 86399 THEN
SET rv = CONCAT(FORMAT(diff/3600, 0), ' hrs ago');
END IF;
IF diff > 86400 THEN
SET rv = DATE_FORMAT(GivenTimestamp, '%a %l:%i %p');
END IF;
IF diff > 259200 THEN
SET rv = DATE_FORMAT(GivenTimestamp, '%b %e at %l:%i %p');
END IF;
RETURN rv;
END $$
DELIMITER ;
Once the function was created I could now use it in the query like so:
SELECT id, name, email, status, GetTimeDisplay(dataTime);
You would received a result similar to:
1 Joe Smith jsmith@test.com Watching TV 34 mins ago
I have been using this function for a few months now and it works wonders. You may tweak it a bit more for your needs. This function also works for future dates similar to 1 hr from now.