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

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

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


当前回答

Day.js

如果你使用day.js,试试这个。

const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration') 
dayjs.extend(duration)

const time = dayjs.duration(100, 'seconds')

time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40

其他回答

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

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

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

很好,很短

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

使用ES6清洁一个衬垫


const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);

我发现的最简洁的方法只用一行就可以完成:

let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`

解释

“${…}的模板文字。允许表达式从字符串本身转换为字符串。注:IE不兼容。

timeInSeconds/60|0将秒转换为分钟(/60)。这给出了一个有理数。从这里开始使用按位OR(|0)进行截断

timeInSeconds % 60余(模)。给出变量的余数除以60。


小时

这种方法可以扩展到包括这样的时间:

let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`

重复这个过程,你甚至可以加上天。