将秒转换为人类可读的持续时间 [英] Convert seconds to human readable time duration

查看:111
本文介绍了将秒转换为人类可读的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何最好地将90060(秒)转换为字符串"25h 1m"?

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

目前,我正在用SQL执行此操作:

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 :-)

我愿意在SQL(不同于我已经在做的)或PHP中做到这一点.

I'm open to suggestions on doing this both in SQL (differently than I'm already doing) or in PHP.

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

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

推荐答案

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

这篇关于将秒转换为人类可读的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆