javascript – 将时间分成几分钟和几秒钟

我有以下代码,应该做我需要的:

function fromSeconds(seconds, showHours = false) {
    if(showHours) {
        var hours = Math.floor(seconds / 3600),
            seconds = seconds - hours * 3600;
    }
    var minutes = (Math.floor(seconds/60) < 10) ? 
        "0" + Math.floor(seconds/60) : Math.floor(seconds/60);
    var seconds = (seconds % 60 > 9) ? seconds % 60 : "0" + seconds % 60;

    if(showHours) {
        var timestring = hours + ":" + minutes + ":" + seconds;
    } else {
        var timestring = minutes + ":" + seconds;
    }
    return timestring;
}

问题是我也有这个:

var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function() {
    $('#currentTime').html(video[0].currentTime.toFixed(2));
    $('#remTime').html((video[0].duration - video[0].currentTime).toFixed(2));
    $('#totalTime').html(video[0].duration.toFixed(2));
});

我不知道如何应用第一个代码,以便例如currentTime显示如下:minutes:seconds.

有什么帮助吗?

最佳答案 通过小固定,您可以将其保留为:

Demo

function fromSeconds(seconds, showHours) {
    if(showHours) {
        var hours = Math.floor(seconds / 3600),
            seconds = seconds - hours * 3600;
    }
    var minutes = ("0" + Math.floor(seconds/60)).slice(-2);
    var seconds = ("0" + parseInt(seconds%60,10)).slice(-2);

    if(showHours) {
        var timestring = hours + ":" + minutes + ":" + seconds;
    } else {
        var timestring = minutes + ":" + seconds;
    }
    return timestring;
}

var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
    $('#currentTime').html(fromSeconds(video[0].currentTime));
    $('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
    $('#totalTime').html(fromSeconds(video[0].duration));
});
点赞