This question already has answers here:
PHP: producing relative date/time from timestamps
(8个答案)
6年前关闭。
我尝试从MySQL
或使用此存储的功能:
查询:
显示:
(8个答案)
6年前关闭。
我尝试从MySQL
NOW()
函数获取相对日期和时间(例如2秒前,3天前,12月31日……),但我不知道该怎么做!有任何想法吗?非常感谢! 最佳答案
使用TIMESTAMPDIFF()
功能。参见示例:
SELECT
TIMESTAMPDIFF(SECOND, `stamp_column`, NOW()) as `seconds`
FROM
`YourTable`
或使用此存储的功能:
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
查询:
SELECT
`PassedSince`('2013-06-19 08:00') as `result`
UNION ALL
SELECT
`PassedSince`('2013-01-01 00:00')
显示:
result
--------------------------------------
1 Hours 20 Minutes 55 Seconds
169 Days 9 Hours 20 Minutes 55 Seconds
10-07 12:37