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

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

    I loved Powtac's answer, but I wanted to use it in angular.js, so I created a filter using his code.

    .filter('HHMMSS', ['$filter', function ($filter) {
        return function (input, decimals) {
            var sec_num = parseInt(input, 10),
                decimal = parseFloat(input) - sec_num,
                hours   = Math.floor(sec_num / 3600),
                minutes = Math.floor((sec_num - (hours * 3600)) / 60),
                seconds = sec_num - (hours * 3600) - (minutes * 60);
    
            if (hours   < 10) {hours   = "0"+hours;}
            if (minutes < 10) {minutes = "0"+minutes;}
            if (seconds < 10) {seconds = "0"+seconds;}
            var time    = hours+':'+minutes+':'+seconds;
            if (decimals > 0) {
                time += '.' + $filter('number')(decimal, decimals).substr(2);
            }
            return time;
        };
    }])
    

    It's functionally identical, except that I added in an optional decimals field to display fractional seconds. Use it like you would any other filter:

    {{ elapsedTime | HHMMSS }} displays: 01:23:45

    {{ elapsedTime | HHMMSS : 3 }} displays: 01:23:45.678

提交回复
热议问题