当我将秒数 165
转换为像 02:45
这样的时间格式时,我得到了错误的答案 1 小时加上小时部分 3:45
。
我不知道实际问题在哪里。
console.log(ConvertStringToTimeFormat(165));
function ConvertStringToTimeFormat(timeString) {
var timeFormat = "";
if (timeString != null && timeString != null != "") {
if (Math.round((parseInt(timeString) / 60)) > 0)
timeFormat += Math.round((parseInt(timeString) / 60)) + ":";
else
timeFormat += "00:";
if ((parseInt(timeString) % 60) > 0)
timeFormat += (parseInt(timeString) % 60);
else
timeFormat += "00";
}
else {
timeFormat = "00:00";
}
return timeFormat;
}
而且当秒数为 125 时,我得到 2:5
作为答案,但我需要 02:05
提前致谢。
最佳答案
您可以为部分使用数组并获取填充的字符串并将结果与 :
连接。
function convert(min) {
return [Math.floor(min / 60), min % 60].map(function (a) { return ('00' + a).slice(-2); }).join(':');
}
console.log(convert(165));
ES6
function convert(min) {
return [Math.floor(min / 60), min % 60].map(a => ('00' + a).slice(-2)).join(':');
}
console.log(convert(165));
关于javascript - 将秒数转换为时间格式时得到错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42998395/