Get relative date from the NOW() function [duplicate]

你。 提交于 2019-11-28 13:13:31

Use TIMESTAMPDIFF() function. See example:

SELECT
    TIMESTAMPDIFF(SECOND, `stamp_column`, NOW()) as `seconds`
FROM
    `YourTable`

Or use this stored function:

CREATE FUNCTION `PassedSince`(`stamp` TIMESTAMP)
RETURNS VARCHAR(100)
DETERMINISTIC
BEGIN
DECLARE `result` VARCHAR(100) DEFAULT '';
DECLARE `seconds`, `minutes`, `hours`, `days` INT;

SET `seconds` = TIMESTAMPDIFF(SECOND, `stamp`, NOW());

SET `days`    = `seconds` DIV (24 * 60 * 60);
SET `seconds` = `seconds` MOD (24 * 60 * 60);

IF `days` > 0
THEN SET `result` = CONCAT(`result`, `days`, ' Days ');
END IF;

SET `hours`   = `seconds` DIV (60 * 60);
SET `seconds` = `seconds` MOD (60 * 60);

IF `hours` > 0
THEN SET `result` = CONCAT(`result`, `hours`, ' Hours ');
END IF;

SET `minutes` = `seconds` DIV 60;
SET `seconds` = `seconds` MOD 60;

IF `minutes` > 0
THEN SET `result` = CONCAT(`result`, `minutes`, ' Minutes ');
END IF;

IF `seconds` > 0
THEN SET `result` = CONCAT(`result`, `seconds`, ' Seconds ');
END IF;

RETURN TRIM(`result`);
END

For query:

SELECT
    `PassedSince`('2013-06-19 08:00') as `result`
UNION ALL
SELECT
    `PassedSince`('2013-01-01 00:00')

Shows:

result
--------------------------------------
1 Hours 20 Minutes 55 Seconds
169 Days 9 Hours 20 Minutes 55 Seconds

You must specify the time, or in your case the seconds, beforehand.

Let me illustrate what I mean, with simple example, based on a PDO-Mysql query

$time = '0:01:00'; // one minute

$stmt = $conn->prepare("SELECT chat_user FROM chatters  
                        WHERE TIMEDIFF(NOW(), login_time) < TIME (?) );

In the above example, if you use the query, you will actually be searching for a user whose login time, is less than $time or 01:00:00

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!