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

前端 未结 30 1791
太阳男子
太阳男子 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 07:23

    Variation on a theme. Handles single digit seconds a little differently

    seconds2time(0)  ->  "0s" 
    seconds2time(59) -> "59s" 
    seconds2time(60) -> "1:00" 
    seconds2time(1000) -> "16:40" 
    seconds2time(4000) -> "1:06:40"
    
    function seconds2time (seconds) {
        var hours   = Math.floor(seconds / 3600);
        var minutes = Math.floor((seconds - (hours * 3600)) / 60);
        var seconds = seconds - (hours * 3600) - (minutes * 60);
        var time = "";
    
        if (hours != 0) {
          time = hours+":";
        }
        if (minutes != 0 || time !== "") {
          minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
          time += minutes+":";
        }
        if (time === "") {
          time = seconds+"s";
        }
        else {
          time += (seconds < 10) ? "0"+seconds : String(seconds);
        }
        return time;
    }
    

提交回复
热议问题