JavaScript seconds to time string with format hh:mm:ss

前端 未结 30 1833
太阳男子
太阳男子 2020-11-22 07:19

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

I found some useful answers here but they all talk about conv

30条回答
  •  Happy的楠姐
    2020-11-22 07:45

    I liked Webjins answer the most, so i extended it to display days with a d suffix, made display conditional and included a s suffix on plain seconds:

    function sec2str(t){
        var d = Math.floor(t/86400),
            h = ('0'+Math.floor(t/3600) % 24).slice(-2),
            m = ('0'+Math.floor(t/60)%60).slice(-2),
            s = ('0' + t % 60).slice(-2);
        return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');
    }
    

    returns "3d 16:32:12" or "16:32:12" or "32:12" or "12s"

提交回复
热议问题