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

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秒= 60; var measuredTime =新的日期(空); measuredTime.setSeconds(秒);//指定SECONDS的值 var Time = measuredTime.toISOString()。8 substr(11日); . getelementbyid (id1”)。value =时间; < div class = "形式的班级”> <label for="course" class="col-md-4">Time</label> . < div class = " col-md-8”> <input type="text" class="form-control" id="id1" name="field">最小值 < / div > < / div >

其他回答

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

另一种更优雅的解决方案如下:

/**
 * Convert number secs to display time
 *
 * 65 input becomes 01:05.
 *
 * @param Number inputSeconds Seconds input.
 */
export const toMMSS = inputSeconds => {
    const secs = parseInt( inputSeconds, 10 );
    let minutes = Math.floor( secs / 60 );
    let seconds = secs - minutes * 60;

    if ( 10 > minutes ) {
        minutes = '0' + minutes;
    }
    if ( 10 > seconds ) {
        seconds = '0' + seconds;
    }

    // Return display.
    return minutes + ':' + seconds;
};

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

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

很好,很短

另一个奇妙的解决方案:

function fancyTimeFormat(duration) { // Hours, minutes and seconds const hrs = ~~(duration / 3600); const mins = ~~((duration % 3600) / 60); const secs = ~~duration % 60; // Output like "1:01" or "4:03:59" or "123:03:59" let ret = ""; if (hrs > 0) { ret += "" + hrs + ":" + (mins < 10 ? "0" : ""); } ret += "" + mins + ":" + (secs < 10 ? "0" : ""); ret += "" + secs; return ret; } console.log( fancyTimeFormat(1), fancyTimeFormat(10), fancyTimeFormat(100), fancyTimeFormat(1000), fancyTimeFormat(10000), );

~~是Math的缩写。楼层,请参阅此链接以获取更多信息

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