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

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

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


当前回答

2019年最佳变种

格式hh: mm: ss

Console.log (display(60 * 60 * 2.5 + 25)) // 2.5小时+ 25秒 功能显示(秒){ const format = val => ' 0${Math.floor(val)} ' .slice(-2) Const hours = seconds / 3600 Const minutes = (seconds % 3600) / 60 返回[hours, minutes, seconds % 60].map(format).join(':') }

其他回答

在这一切之后,还有一个简单的解决方案:

const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());

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

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));

Var秒= 60; var measuredTime =新的日期(空); measuredTime.setSeconds(秒);//指定SECONDS的值 var Time = measuredTime.toISOString()。8 substr(11日); . getelementbyid (id1”)。value =时间; < div class = "形式的班级”> <label for="course" class="col-md-4">Time</label> . < div class = " col-md-8”> <input type="text" class="form-control" id="id1" name="field">最小值 < / div > < / div >

你也可以使用本机Date对象:

var date = new Date(null);
date.setSeconds(timeInSeconds);

// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)

// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' +  date.getUTCSeconds();

// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);

// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);

当然,这个解决方案只适用于小于24小时的timeInSeconds;)

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

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

很好,很短