这是一个常见的问题,但我不知道如何解决它。下面的代码可以正常工作。
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 mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
然而,当我到达1小时或3600秒时,它返回0分和0秒。我如何避免这种情况,让它返回所有的分钟?
当前回答
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`;
}
其他回答
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
要得到完整的分钟数,将总秒数除以60(60秒/分钟):
const minutes = Math.floor(time / 60);
为了得到剩余的秒数,将整个分钟数乘以60,然后减去总秒数:
const seconds = time - minutes * 60;
现在,如果你也想得到完整的小时数,首先用总秒数除以3600(60分钟/小时·60秒/分钟),然后计算剩余的秒数:
const hours = Math.floor(time / 3600);
time = time - hours * 3600;
然后计算完整的分钟数和剩余的秒数。
奖金:
使用以下代码来漂亮地打印时间(由Dru建议):
function str_pad_left(string, pad, length) {
return (new Array(length + 1).join(pad) + string).slice(-length);
}
const finalTime = str_pad_left(minutes, '0', 2) + ':' + str_pad_left(seconds, '0', 2);
试试这个: 将秒转换为小时,分钟和秒。
function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
}
这是一个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(秒)); }
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`;
}