【问题标题】:Converting seconds to HH:mm:ss?将秒转换为 HH:mm:ss?
【发布时间】:2016-08-16 05:26:37
【问题描述】:

当我尝试将秒数转换为 hh:mm:ss 格式时,我的小时数超过了两个字符。

var seconds = 4287050531;
var getTime = formatTime(seconds);
console.log("Time Is :"+getTime);// 1190847:22:11 

function formatTime(seconds) {
  return [pad(Math.floor(seconds/3600)),
          pad(Math.floor(seconds/60)%60),
          pad(seconds%60),
          ].join(":");
}

function pad(num) {
  if(num < 10) {
    return "0" + num;
  } else {
    return "" + num;
  }
}

【问题讨论】:

  • 你想达到什么结果?截断超过 24 小时的任何时间?
  • 我也使用了 24 但显示错误的结果,函数 formatTime(seconds) { return [pad(Math.floor(seconds/3600)%24), pad(Math.floor(seconds/60)% 60), pad(秒%60), ].join(":"); }
  • 预期结果是什么
  • @shreyaS 告诉我们您的预期结果应该是什么。因为通常这种格式用于显示一天的时间,所以一天中的最大秒数可以是60*60*24,即86400,但你的第二个变量超过了这个值。所以这就是为什么你的小时数超过了两个字符。
  • 在您的示例中,小时绝对可以 > 99,因为输入以秒为单位,而 input/3600 可以是任何基于您输入的数字。

标签: javascript jquery node.js time momentjs


【解决方案1】:

你能试试下面的功能吗:

 function convert(seconds) {
    seconds = Number(seconds);
    var hours = Math.floor(seconds / 3600);
    var minutes = Math.floor(seconds % 3600 / 60);
    var seconds = Math.floor(seconds % 3600 % 60);
    return ((hours > 0 ? hours + ":" + (minutes < 10 ? "0" : "") : "") + minutes + ":" + (seconds < 10 ? "0" : "") +`enter code here` seconds); 
}

【讨论】:

    【解决方案2】:

    为什么不使用 moment-duration-format 模块

    npm install moment-duration-format
    
    var moment = require("moment-duration-format");
    
    moment.duration(seconds, "seconds").format("h:m:s");
    

    https://github.com/jsmreese/moment-duration-format

    【讨论】:

    • 未捕获的类型错误:moment.duration(...).format 不是函数
    • 需要模块时刻。
    【解决方案3】:

    为什么要这么麻烦?

    试试这个:

    (function () {
      
        function checkTime(i) {
            return (i < 10) ? "0" + i : i;
        }
    
        function startTime() {
            var today = new Date(),
                h = checkTime(today.getHours()),
                m = checkTime(today.getMinutes()),
                s = checkTime(today.getSeconds());
                return h + ":" + m + ":" + s;
            
           
        }
       setInterval(function () {
                document.getElementById('yourTime').innerHTML =  startTime();
            }, 1000);
      
    })();
    &lt;div id="yourTime"&gt;

    【讨论】:

    • 如果秒数加起来超过 24 小时,这将不起作用。
    【解决方案4】:

    尝试使用datejs

    使用这个可以很方便的转换它

    (new Date).clearTime()
              .addSeconds(4287050531)
              .toString('H:mm:ss');
    

    【讨论】:

    • 我收到 Uncaught TypeError: (intermediate value).clearTime 不是函数
    • 先添加 date.js 文件然后试试这个
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 2011-10-30
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多