javascript 如何用前导零显示时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12230343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:40:07  来源:igfitidea点击:

How can I display time with leading zeros?

javascriptdatetimetime

提问by sammyukavi

I have created a time function to calculate time as media is playing. It does not display any leading zeros. How can I make it display any leading zeros?

我创建了一个时间函数来计算媒体播放的时间。它不显示任何前导零。我怎样才能让它显示任何前导零?

function converttoTime(timeInSeconds)
   {
    var minutes = Math.round(Math.floor(timeInSeconds / 60));
    var seconds = Math.round(timeInSeconds - minutes * 60);
    //var hours = Math.round(Math.floor(timeInSeconds / 3600));
    //time = time - hours * 3600;
    var time=minutes+':'+seconds;
    return time;
   }

回答by Ankur

this should work:

这应该有效:

var time=('0'  + minutes).slice(-2)+':'+('0' + seconds).slice(-2);