MySQL 将秒转换为人类可读的持续时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8193868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert seconds to human readable time duration
提问by Henno
How would I best convert 90060 (seconds) to a string of "25h 1m"?
我如何最好地将 90060(秒)转换为“25h 1m”的字符串?
Currently I'm doing this in SQL:
目前我在 SQL 中这样做:
SELECT
IF(
HOUR(
sec_to_time(
sum(time_to_sec(task_records.time_spent))
)
) > 0,
CONCAT(
HOUR(sec_to_time(sum(time_to_sec(task_records.time_spent)))),
'h ',
MINUTE(sec_to_time(sum(time_to_sec(task_records.time_spent)))),
'm'
),
CONCAT(
MINUTE(sec_to_time(sum(time_to_sec(task_records.time_spent)))),
'm'
)
) as time
FROM myTable;
But I'm not sure it's the most convenient method :-)
但我不确定这是最方便的方法:-)
I'm open to suggestions on doing this both in SQL (differently than I'm already doing) or in PHP.
我愿意接受在 SQL(与我已经在做的不同)或 PHP 中执行此操作的建议。
EDIT:
编辑:
Examples of desired strings: "5m", "40m", "1h 35m", "45h" "46h 12m".
所需字符串的示例:“5m”、“40m”、“1h 35m”、“45h”、“46h 12m”。
回答by Peter
TIME_FORMAT(SEC_TO_TIME(task_records.time_spent),'%Hh %im')
Documentation is your friend:
文档是您的朋友:
According to comment:
根据评论:
DROP FUNCTION IF EXISTS GET_HOUR_MINUTES;
CREATE FUNCTION GET_HOUR_MINUTES(seconds INT)
RETURNS VARCHAR(16)
BEGIN
DECLARE result VARCHAR(16);
IF seconds >= 3600 THEN SET result = TIME_FORMAT(SEC_TO_TIME(seconds),'%kh %lm');
ELSE SET result = TIME_FORMAT(SEC_TO_TIME(seconds),'%lm');
RETURN result;
END
DELIMETER ;
Usage:
用法:
SELECT GET_HOUR_MINUTES(task_records.time_spent) FROM table
回答by rrawat
you can use predefined function sec_to_time()
您可以使用预定义的函数 sec_to_time()
sec_to_time(number_of_seconds)
sec_to_time(number_of_seconds)
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_sec-to-time
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_sec-to-time
回答by Smit Shilpatul
try this: (input your pure seconds time)
试试这个:(输入你的纯秒时间)
var hours = Math.floor(input/3600);
var minutes = Math.floor((input-hours*3600)/60);
var seconds = input-(minutes*60)-(hours*3600);
function convertTime(){
return hours":"minutes":"seconds;
}