timeAgo Function in MySQL

Almost everyone who works in this field is familiar with the PHP timeAgo functions.What was this function doing? You were giving a date in this format Y-m-d H:i:s and it was returning you a result such as 2 days ago, 3 hours ago, 1 year ago.

How can we write as MySQL function without using PHP escatly the same? Here is the has been written function sample.

DELIMITER $$

DROP FUNCTION IF EXISTS `timeAgo`$$

CREATE FUNCTION `timeAgo`(dateColumn DATETIME) RETURNS VARCHAR(100) CHARSET utf8
BEGIN

	DECLARE result VARCHAR(100) DEFAULT '';
	DECLARE difference INT(11);
	
	SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(dateColumn) INTO difference;
	
	IF difference  > 60 * 60 * 24 * 7 * 4 * 12
		THEN SELECT CONCAT(ROUND(difference / 60 / 60 / 24 / 7 / 4 / 12), " year ago") INTO result;
	ELSEIF difference > 60 * 60 * 24 * 7 * 4
		THEN SELECT CONCAT(ROUND(difference / 60 / 60 / 24 / 7 / 4), " month ago") INTO result;
	ELSEIF difference > 60 * 60 * 24 * 7
		THEN SELECT CONCAT(ROUND(difference / 60 / 60 / 24 / 7), " week ago") INTO result;
	ELSEIF difference > 60 * 60 * 24
		THEN SELECT CONCAT(ROUND(difference / 60 / 60 / 24), " day ago") INTO result;
	ELSEIF difference > 60 * 60
		THEN SELECT CONCAT(ROUND(difference / 60 / 60), " hour ago") INTO result;
	ELSEIF difference > 60
		THEN SELECT CONCAT(ROUND(difference / 60), " minute ago") INTO result;
	ELSEIF difference > 0
		THEN SELECT CONCAT(difference , " second ago") INTO result;
	ELSE
		SELECT "just before" INTO result;
	END IF;
	
	RETURN result;
	
END$$

DELIMITER ;

After running for once this function will be saved in your database. For SELECT operations you may use in this way;

SELECT user_name, timeAgo(user_date) as date FROM users

 

Comments

There are no comments, make the firs comment