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

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

其他回答

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

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

很好,很短

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

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

}

(使用Vishal的代码)

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

使用ES6清洁一个衬垫


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

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