如何使用JavaScript将秒转换为HH-MM-SS字符串?


当前回答

已经有很多答案了,但我的要求是:

转换为持续时间(即,应适用于大于24小时的值) 关心的小数秒到给定的十进制精度 如果为零,则截断前面的小时和分钟。

const seconds2duration = ( seconds, decimals=0 ) => { let fraction = ( seconds - Math.floor( seconds ) ).toFixed( decimals ); fraction = decimals === 0 ? '' : fraction.slice( 1 ); const [ hours, mins, secs ] = [ seconds / 3600, seconds % 3600 / 60, seconds % 3600 % 60 ].map( ( x ) => String( Math.floor( x ) ).padStart( 2, '0' ) ); if ( hours === '00' && mins === '00' ) { return secs + fraction; } else if ( hours === '00' ) { return [ mins, secs + fraction ].join( ':' ); } else { return [ hours, mins, secs + fraction ].join( ':' ); } }; console.log(seconds2duration(25*3600 + 0*60 + 41 + 0.333, 0)); // 25:00:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 0)); // 05:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 1)); // 05:41.3 console.log(seconds2duration(0*3600 + 0*60 + 41 + 0.333, 2)); // 41.33

其他回答

更新(2020):

请使用@Frank的一句话解决方案:

new Date(SECONDS * 1000).toISOString().substring(11, 16)

如果SECONDS<3600并且你只想显示MM:SS,那么使用下面的代码:

new Date(SECONDS * 1000).toISOString().substring(14, 19)

这是目前为止最好的解决办法。


旧的回答:

使用Moment.js库。

我只是想对上面这个不错的答案做一点解释:

var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;

var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);

On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.

当你看到这样的东西:

25 % 24

你可以这样想:

25 mod 24 or what is the remainder when we divide 25 by 24

你也可以用Sugar。

Date.create().reset().set({seconds: 180}).format('{mm}:{ss}');

这个例子返回'03:00'。

正如Cleiton在他的回答中指出的,moment.js可以用于:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

这里有一个转换时间的简单函数,可能会有帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}