问题描述
我想将MM:SS格式的秒转换为分钟和秒。下面的代码工作正常,但将秒转换为M:SS格式。如何将其更改为MM:SS格式。
例如,将150 seconds
传递给format(150)
时得到2:30
,但我需要像02:30
function format(time) {
// Hours,minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
var ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
解决方法
您可以将padStart
用于min
ret += "" + String(mins).padStart(2,'0') + ":" + (secs < 10 ? "0" : "");
function format(time) {
// Hours,minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
var ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + String(mins).padStart(2,'0') + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
console.log(format(150))
,
您可以使用此
ret = (hrs>0?("" + hrs + ":"):"") + (mins < 10 ? "0"+mins : mins) + ":" + (secs < 10 ? "0"+secs : secs);
,
请尝试:
ret = (hrs ? hrs + ":" : '') + ("0" + mins).slice(-2) + ":" + ("0" + secs).slice(-2)
Goodluck:D