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

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

其他回答

Moment.js

如果你使用的是Moment.js,那么你可以使用内置的Duration对象

const duration = moment.duration(4825, 'seconds');

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25

strftime.js (strftime github)是最好的时间格式库之一。它非常轻——30KB——而且非常有效。使用它,您可以在一行代码中轻松地将秒转换为时间,主要依赖于本机Date类。

当创建一个新的Date时,每个可选参数的位置如下:

new Date(year, month, day, hours, minutes, seconds, milliseconds);

因此,如果你初始化一个new Date,所有参数都为0,直到秒,你会得到:

var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)

可以看到150秒是2分钟和30秒,如创建的日期所示。然后使用strftime格式(“MM:SS”为“%M:%S”),它将输出您的分钟字符串。

var mm_ss_str = strftime("%M:%S", date);
=> "02:30"

在一行中,它看起来像这样:

var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"

另外,这将允许您根据秒数交换支持HH:MM:SS和MM:SS。例如:

# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"

# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"

当然,如果您希望时间字符串或多或少具有语义,您可以简单地将您想要的任何格式传递给strftime。

var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"

要得到完整的分钟数,将总秒数除以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 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`;
}