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

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

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


当前回答

我在想一个更快的方法来完成这件事,这就是我想到的

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

如果我们想要将“时间”转换为分钟和秒,例如:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1

其他回答

这是一个ES6版本的秒到分钟和秒的转换,带有填充(00:00格式)。它只接受整数值的秒和~~(x)是速记地板操作。

const padTime = n => (" + n).padStart(2,0); const secondsToMinSec = time => “$ {padTime(~ ~(时间/ 60)}:$ {padTime(时间- ~ ~(时间/ 60)* 60)}” ; 对于(设I = 0;I < 10;我+ +){ const seconds = ~~(Math.random() * 300); console.log(秒,secondsToMinSec(秒)); }

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

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`;
}

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(':') }

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

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

}

(使用Vishal的代码)