Convert seconds to human readable time duration

扶醉桌前 提交于 2019-11-26 16:33:42

问题


How would I best convert 90060 (seconds) to a string of "25h 1m"?

Currently I'm doing this in 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.

EDIT:

Examples of desired strings: "5m", "40m", "1h 35m", "45h" "46h 12m".


回答1:


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

Documentation is your friend:

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

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



回答2:


you can use predefined function 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




回答3:


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


来源:https://stackoverflow.com/questions/8193868/convert-seconds-to-human-readable-time-duration

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