JavaScript 秒到时间字符串,格式为 hh:mm:ss [英] JavaScript seconds to time string with format hh:mm:ss

查看:27
本文介绍了JavaScript 秒到时间字符串,格式为 hh:mm:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将持续时间(即秒数)转换为以冒号分隔的时间字符串 (hh:mm:ss)

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

我在这里找到了一些有用的答案,但他们都在谈论转换为 x 小时 x 分钟格式.

I found some useful answers here but they all talk about converting to x hours and x minutes format.

那么是否有一个小片段可以在 jQuery 或原始 JavaScript 中执行此操作?

So is there a tiny snippet that does this in jQuery or just raw JavaScript?

推荐答案

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

您现在可以像这样使用它:

You can use it now like:

alert("5678".toHHMMSS());

工作片段:

String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours + ':' + minutes + ':' + seconds;
}
    
console.log("5678".toHHMMSS());

这篇关于JavaScript 秒到时间字符串,格式为 hh:mm:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆