这是一个常见的问题,但我不知道如何解决它。下面的代码可以正常工作。

var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
         
var secd = mind % 60;
var seconds = Math.ceil(secd);

然而,当我到达1小时或3600秒时,它返回0分和0秒。我如何避免这种情况,让它返回所有的分钟?


当前回答

要添加前导零,我只需这样做:

const secondstom昆虫填充=时间=> { const minutes = "0" + Math。楼层(时间/ 60); Const seconds = "0" +(时间-分钟* 60); 返回minutes.substr(-2) + ":" + seconds.substr(-2); }; console.log (secondsToMinSecPadded (241));

很好,很短

其他回答

另一个奇妙的解决方案:

function fancyTimeFormat(duration) { // Hours, minutes and seconds const hrs = ~~(duration / 3600); const mins = ~~((duration % 3600) / 60); const secs = ~~duration % 60; // Output like "1:01" or "4:03:59" or "123:03:59" let ret = ""; if (hrs > 0) { ret += "" + hrs + ":" + (mins < 10 ? "0" : ""); } ret += "" + mins + ":" + (secs < 10 ? "0" : ""); ret += "" + secs; return ret; } console.log( fancyTimeFormat(1), fancyTimeFormat(10), fancyTimeFormat(100), fancyTimeFormat(1000), fancyTimeFormat(10000), );

~~是Math的缩写。楼层,请参阅此链接以获取更多信息

function secondsToMinutes(time){
    return Math.floor(time / 60)+':'+Math.floor(time % 60);
}

您已经编写了足够多的代码来跟踪时间的分钟和秒部分。

你可以把时间因素加进去:

var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);

var mind = hrd % 60;
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

var moreminutes = minutes + hours * 60

秒到h:mm:ss

var hours = Math.floor(time / 3600);
time -= hours * 3600;

var minutes = Math.floor(time / 60);
time -= minutes * 60;

var seconds = parseInt(time % 60, 10);

console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));

下面的函数将帮助您获得日,小时,分钟,秒

toDDHHMMSS(inputSeconds){
        const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
        const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
        const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
        const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
        let ddhhmmss  = '';
        if (Days > 0){
            ddhhmmss += Days + ' Day ';
        }
        if (Hour > 0){
            ddhhmmss += Hour + ' Hour ';
        }

        if (Minutes > 0){
            ddhhmmss += Minutes + ' Minutes ';
        }

        if (Seconds > 0){
            ddhhmmss += Seconds + ' Seconds ';
        }
        return ddhhmmss;
    }
alert( toDDHHMMSS(2000));