javascript - 将秒数转换为时间格式时得到错误答案

标签 javascript

当我将秒数 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/

相关文章:

javascript - 使用 $ImageCacheFactory 预加载所有图像

javascript - 如何使用 react-sortable-hoc (Table) 自动滚动?

javascript - Fancybox 字幕位置

javascript - controllerAs 在指令的链接功能中不起作用

javascript - 字符串中棘手的多次替换

javascript - 使用 str.replace() 在 JavaScript 字符串中插入 "."

javascript - Angular.js ng-repeat 使用 json 没有数据

javascript - 在 JavaScript 中创建新的数据类型

javascript - 一个一个地为一组元素设置阴影动画

javascript - CSS 动画,点击时切换旋转