将秒转换为人类可读的持续时间

时间:2011-11-19 11:53:43

标签: mysql time duration

我如何才能最好地将90060(秒)转换为" 25h 1m"?

目前我在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;

但我不确定它是最方便的方法: - )

我愿意接受在SQL(不同于我已经在做)或PHP中这样做的建议。

编辑:

所需字符串的示例:" 5m"," 40m"," 1h 35m"," 45h" " 46h 12m"。

3 个答案:

答案 0 :(得分:48)

TIME_FORMAT(SEC_TO_TIME(task_records.time_spent),'%Hh %im')

文档是你的朋友:


根据评论:

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 ;

用法:

SELECT GET_HOUR_MINUTES(task_records.time_spent) FROM table

答案 1 :(得分:3)

您可以使用预定义的函数sec_to_time()

SEC_TO_TIME(NUMBER_OF_SECONDS)

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_sec-to-time

答案 2 :(得分:-3)

试试这个:(输入你的纯秒时间)

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;
}