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

前端 未结 30 1413
太阳男子
太阳男子 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:44

    Here is yet another version, which handles days also:

    function FormatSecondsAsDurationString( seconds )
    {
        var s = "";
    
        var days = Math.floor( ( seconds / 3600 ) / 24 );
        if ( days >= 1 )
        {
            s += days.toString() + " day" + ( ( days == 1 ) ? "" : "s" ) + " + ";
            seconds -= days * 24 * 3600;
        }
    
        var hours = Math.floor( seconds / 3600 );
        s += GetPaddedIntString( hours.toString(), 2 ) + ":";
        seconds -= hours * 3600;
    
        var minutes = Math.floor( seconds / 60 );
        s += GetPaddedIntString( minutes.toString(), 2 ) + ":";
        seconds -= minutes * 60;
    
        s += GetPaddedIntString( Math.floor( seconds ).toString(), 2 );
    
        return s;
    }
    
    function GetPaddedIntString( n, numDigits )
    {
        var nPadded = n;
        for ( ; nPadded.length < numDigits ; )
        {
            nPadded = "0" + nPadded;
        }
    
        return nPadded;
    }
    
    0 讨论(0)
  • 2020-11-22 07:45
    function formatTime(seconds) {
        return [
            parseInt(seconds / 60 / 60),
            parseInt(seconds / 60 % 60),
            parseInt(seconds % 60)
        ]
            .join(":")
            .replace(/\b(\d)\b/g, "0$1")
    }
    
    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2020-11-22 07:45

    Here's a one-liner updated for 2019:

    //your date
    var someDate = new Date("Wed Jun 26 2019 09:38:02 GMT+0100") 
    
    var result = `${String(someDate.getHours()).padStart(2,"0")}:${String(someDate.getMinutes()).padStart(2,"0")}:${String(someDate.getSeconds()).padStart(2,"0")}`
    
    //result will be "09:38:02"
    
    0 讨论(0)
  • 2020-11-22 07:46

    I'm personally prefer the leading unit (days, hours, minutes) without leading zeros. But seconds should always be leaded by minutes (0:13), this presentation is easily considered as 'duration', without further explanation (marking as min, sec(s), etc.), usable in various languages (internationalization).

        // returns  (-)d.h:mm:ss(.f)
        //          (-)h:mm:ss(.f)
        //          (-)m:ss(.f)
        function formatSeconds (value, fracDigits) {
            var isNegative = false;
            if (isNaN(value)) {
                return value;
            } else if (value < 0) {
                isNegative = true;
                value = Math.abs(value);
            }
            var days = Math.floor(value / 86400);
            value %= 86400;
            var hours = Math.floor(value / 3600);
            value %= 3600;
            var minutes = Math.floor(value / 60);
            var seconds = (value % 60).toFixed(fracDigits || 0);
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
    
            var res = hours ? (hours + ':' + ('0' + minutes).slice(-2) + ':' + seconds) : (minutes + ':' + seconds);
            if (days) {
                res = days + '.' + res;
            }
            return (isNegative ? ('-' + res) : res);
        }
    

    //imitating the server side (.net, C#) duration formatting like:

        public static string Format(this TimeSpan interval)
        {
            string pattern;
            if (interval.Days > 0)          pattern = @"d\.h\:mm\:ss";
            else if (interval.Hours > 0)    pattern = @"h\:mm\:ss";
            else                            pattern = @"m\:ss";
            return string.Format("{0}", interval.ToString(pattern));
        }
    
    0 讨论(0)
  • 2020-11-22 07:47

    You can use the following function to convert time (in seconds) to HH:MM:SS format :

    var convertTime = function (input, separator) {
        var pad = function(input) {return input < 10 ? "0" + input : input;};
        return [
            pad(Math.floor(input / 3600)),
            pad(Math.floor(input % 3600 / 60)),
            pad(Math.floor(input % 60)),
        ].join(typeof separator !== 'undefined' ?  separator : ':' );
    }
    

    Without passing a separator, it uses : as the (default) separator :

    time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51
    

    If you want to use - as a separator, just pass it as the second parameter:

    time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46
    

    Demo

    var convertTime = function (input, separator) {
        var pad = function(input) {return input < 10 ? "0" + input : input;};
        return [
            pad(Math.floor(input / 3600)),
            pad(Math.floor(input % 3600 / 60)),
            pad(Math.floor(input % 60)),
        ].join(typeof separator !== 'undefined' ?  separator : ':' );
    }
    
    document.body.innerHTML = '<pre>' + JSON.stringify({
        5.3515555 : convertTime(5.3515555),
        126.2344452 : convertTime(126.2344452, '-'),
        1156.1535548 : convertTime(1156.1535548, '.'),
        9178.1351559 : convertTime(9178.1351559, ':'),
        13555.3515135 : convertTime(13555.3515135, ',')
    }, null, '\t') +  '</pre>';

    See also this Fiddle.

    0 讨论(0)
提交回复
热议问题