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

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

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


当前回答

如果你需要工作的结果很容易,这是我使用:

function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
    seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}

}

(使用Vishal的代码)

其他回答

export function TrainingTime(props) {
    const {train_time } = props;
    const hours = Math.floor(train_time/3600);
    const minutes = Math.floor((train_time-hours * 3600) / 60);
    const seconds = Math.floor((train_time%60));

    return `${hours} hrs  ${minutes} min  ${seconds} sec`;
}

你也可以使用本机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;)

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 >

说说我的意见:

function convertSecondsToMinutesAndSeconds(seconds){
            var minutes;
            var seconds;
            minutes = Math.floor(seconds/60);
            seconds = seconds%60;

            return [minutes, seconds];
        }

所以这个:

var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);

将有以下输出:

[1,41];

然后你可以像这样打印它:

console.log('TIME : ' +  minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');

//TIME : 1 minutes, 41 seconds

一句话(不适合几个小时):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }