【问题标题】:Convert seconds to HH-MM-SS with JavaScript?使用 JavaScript 将秒转换为 HH-MM-SS?
【发布时间】:2010-11-22 07:19:01
【问题描述】:

如何使用 JavaScript 将秒转换为 HH-MM-SS 字符串?

【问题讨论】:

标签: javascript date time date-format time-format


【解决方案1】:

借助 JavaScript Date 方法,您可以在没有任何外部 JavaScript 库的情况下做到这一点,如下所示:

var date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
var result = date.toISOString().substr(11, 8);

或者,根据@Frank的评论;一个班轮:

new Date(SECONDS * 1000).toISOString().substr(11, 8);

【讨论】:

  • 我不知道为什么每个人都在添加额外的库或在完美运行时手动进行数学运算。谢谢!
  • 这甚至可以缩短为一行:new Date(SECONDS * 1000).toISOString().substr(11, 8);
  • 太棒了。没有任何第三方库。这是最好的
  • 这种方式的问题是24小时后会溢出,阻止你展示超过这个时间长度。如果您的秒数少于 24 小时,则是完美的解决方案。
  • 这在 IE11 中对我不起作用,我得到 Object doesn't support property or method 'toISOString'
【解决方案2】:

更新(2020 年):

请使用@Frank 的单行解决方案:

new Date(SECONDS * 1000).toISOString().substr(11, 8)

如果 SECONDS 并且您只想显示 MM:SS 则使用以下代码:

new Date(SECONDS * 1000).toISOString().substr(14, 5)

这是迄今为止最好的解决方案。


旧答案:

使用Moment.js 库。

【讨论】:

  • Granted Moment.js 并没有那么大,但如果你用它做的只是将秒转换为 hh:mm:ss,这似乎有点矫枉过正。而是使用这些或其他答案中建议的功能之一。
  • 这个答案,如果有的话,部分错误。如果数量超过 86400 秒会怎样? ;)
  • 我认为另一种解决方案比混入另一个 js 库要好。
  • 为一个简单的操作添加库我认为不应该被接受。是的,这可行,但有更好的解决方案!!!
  • 使用这个库来完成一个像这样的小任务会将 59,024 bytes 添加到您的项目中,其效果与 53 bytes 将给您带来的效果相同. . .来自belownew Date(SECONDS * 1000).toISOString().substr(11, 8);
【解决方案3】:

我认为标准 Date 对象的任何内置功能都不会以比自己做数学更方便的方式为您执行此操作。

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

例子:

let totalSeconds = 28565;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;

console.log("hours: " + hours);
console.log("minutes: " + minutes);
console.log("seconds: " + seconds);

// If you want strings with leading zeroes:
minutes = String(minutes).padStart(2, "0");
hours = String(hours).padStart(2, "0");
seconds = String(seconds).padStart(2, "0");
console.log(hours + ":" + minutes + ":" + seconds);

【讨论】:

  • 我认为这有一些问题?当我尝试它时,我得到了小数点,所以 180 秒将在 hours 变量中返回 0.05。我把它放在parseInt 中,它为我的情况修复了它,但我不认为这对所有事情都是准确的。不过,这对我有帮助,非常感谢!
  • @BT643:奇怪的是我没有处理这个问题。我现在已经这样做了,您不想为此使用parseInt,那是为了解析字符串,而不是处理数字。 Math.floor 将是这里的相关操作。
  • 啊,好的!更改了我的代码。尽管您可能也希望在几秒钟内获得它:seconds = Math.floor(totalSeconds % 60);。我也在那里得到了一个小数结果。
  • @BT643: totalSeconds % 60 只有在totalSeconds 有小数部分时才能有小数部分。您是否要取消它取决于您是要丢失该信息还是保留它。 (我们正在执行的其他楼层操作不会丢失任何信息,因为它们只是清除最终将在minutesseconds 中的数据。)
  • @HannounYassir console.log( hours +':'+ ('0'+minutes).slice(-2) +':'+ ('0'+seconds).slice(-2) );
【解决方案4】:

我知道这有点老了,但是...

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}

它会输出:

toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18

【讨论】:

  • 几分之一秒呢? 03:45:45.xxx?
  • @SantiagoHernández 太棒了!这现在可以完美运行超过 24 小时。
  • +1。这个或 T.J.应该是公认的答案,因为这些是唯一适用于持续时间超过 24 小时的情况(并且问题不限制持续时间)。
【解决方案5】:

正如克莱顿在his answer 中指出的那样,moment.js 可以用于此:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

【讨论】:

  • 秒数超过一天会怎样?
  • @GiladPeleg 如果秒数超过一天,天数在内部计算,它只会返回剩余的小时、分钟和秒。如果你也想计算天数,你可以试试moment().startOf('year').seconds(30000000).format('DDD HH:mm:ss')
  • 秒数超过一年会怎样?
  • @OrangePot 如果秒数超过一年,则内部计算年数,它只会返回剩余的天数、小时数、分钟数和秒数。如果你也想计算年数,你可以试试.format('YYYY DDD HH:mm:ss')
  • 但这不能成为可选的。那可能看起来很难看。
【解决方案6】:

这是一个用于转换时间的简单函数,可能会有所帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

【讨论】:

  • formatSeconds(3919); //返回 01:05:19 优秀的功能.. 喜欢它
  • 如前所述,24小时后会溢出
【解决方案7】:

这就是诀窍:

function secondstotime(secs)
{
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(0,8);
    if(secs > 86399)
        s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}

(来自here

【讨论】:

    【解决方案8】:
    var  timeInSec = "661"; //even it can be string
    
    String.prototype.toHHMMSS = function () { 
       /* extend the String by using prototypical inheritance */
        var seconds = parseInt(this, 10); // don't forget the second param
        var hours   = Math.floor(seconds / 3600);
        var minutes = Math.floor((seconds - (hours * 3600)) / 60);
        seconds = seconds - (hours * 3600) - (minutes * 60);
    
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var time    = hours+':'+minutes+':'+seconds;
        return time;
    }
    
    alert("5678".toHHMMSS());   // "01:34:38"
    console.log(timeInSec.toHHMMSS());   //"00:11:01"
    

    我们可以使这个函数更短更清晰,但这会降低可读性,所以我们会尽可能简单和稳定地编写它。

    或者你可以检查这个工作here

    【讨论】:

    • 此外......如果你想轻松完成所有日期时间的事情......使用momentJS
    • 谢谢!无需在浏览器扩展中包含库。简单而有效!
    【解决方案9】:

    试试这个:

    function toTimeString(seconds) {
      return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
    }
    

    【讨论】:

      【解决方案10】:

      我认为最通用(和神秘)的解决方案可能是这个

      function hms(seconds) {
        return [3600, 60]
          .reduceRight(
            (pipeline, breakpoint) => remainder =>
              [Math.floor(remainder / breakpoint)].concat(pipeline(remainder % breakpoint)),
            r => [r]
          )(seconds)
          .map(amount => amount.toString().padStart(2, '0'))
          .join('-');
      }
      

      或者复制粘贴最短的版本

      function hms(seconds) {
        return [3600, 60]
          .reduceRight(
            (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
            r => [r]
          )(seconds)
          .map(a => a.toString().padStart(2, '0'))
          .join('-');
      }
      

      一些示例输出:

      > hms(0)
      < "00-00-00"
      
      > hms(5)
      < "00-00-05"
      
      > hms(60)
      < "00-01-00"
      
      > hms(3785)
      < "01-03-05"
      
      > hms(37850)
      < "10-30-50"
      
      > hms(378500)
      < "105-08-20"
      

      工作原理

      算法

      1. 要获得小时数,请将总秒数除以 3600 并取整。
      2. 要获得分钟数,请将余数除以 60 并取底。
      3. 要获得秒数,只需使用余数即可。

      将各个金额保存在一个数组中以便于格式化也很好。

      例如输入 3785s,输出应该是[1, 3, 5],即 1 小时 3 分 5 秒。

      创建管道

      将 3600 和 60 个常量命名为“断点”,您可以将此算法写入函数为 this

      function divideAndAppend(remainder, breakpoint, callback) {
        return [Math.floor(remainder / breakpoint)].concat(callback(remainder % breakpoint));
      }
      

      它返回一个数组,其中第一项是给定断点的数量,数组的其余部分由回调给出。 在回调函数中重用divideAndAppend 将为您提供一个组合的管道 divideAndAppend 函数。这些中的每一个 计算每个给定断点的数量并将其附加到数组中,以产生所需的输出。

      然后您还需要结束此管道的“最终”回调。换句话说,您使用了所有断点,现在您只有剩余的断点。 由于您已经在 3) 处得到了答案,因此您应该使用某种身份函数,在本例中为 remainder =&gt; [remainder]

      您现在可以像这样编写管道

      let pipeline = r3 => divideAndAppend(
          r3, 
          3600, 
          r2 => divideAndAppend(
              r2, 
              60, 
              r1 => [r1]));
      
      > pipeline(3785)
      < [1, 3, 5]
      

      很酷吧?

      使用 for 循环进行泛化

      现在您可以使用可变数量的断点进行概括,并创建一个 for 循环,将单个 divideAndAppend 函数组合成 管道。 您从标识函数r1 =&gt; [r1] 开始,然后使用60 断点,最后使用3600 断点。

      let breakpoints = [60, 3600];
      let pipeline = r => [r];
      
      for (const b of breakpoints) {
        const previousPipeline = pipeline;
        pipeline = r => divideAndAppend(r, b, previousPipeline);
      }
      
      > pipeline(3785)
      < [1, 3, 5]
      

      使用Array.prototype.reduce()

      现在您可以将这个 for 循环重写为 reducer,以获得更短且功能更强大的代码。换句话说,将函数组合重写到reducer中。

      let pipeline = [60, 3600].reduce(
        (ppln, b) => r => divideAndAppend(r, b, ppln),
        r => [r]
      );
      
      > pipeline(3785)
      < [1, 3, 5]
      

      累加器ppln 是管道,您正在使用它的先前版本来组合它。初始管道是r =&gt; [r]

      您现在可以内联函数divideAndAppend 并使用与[].reverse().reduce(...) 相同的Array.prototype.reduceRight 来创建断点 定义更自然。

      let pipeline = [3600, 60]
          .reduceRight(
            (ppln, b) => r => [Math.floor(r / b)].concat(ppln(r % b)),
            r => [r]
          );
      

      这是最终的形式。然后,您只需将映射应用到左侧填充 0 的字符串,并使用 : 分隔符连接字符串;

      更多概括

      将reducer包装成函数

      function decompose(total, breakpoints) {
        return breakpoints.reduceRight(
          (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
          r => [r]
        )(total);
      }
      
      > decompose(3785, [3600, 60])
      < [1, 3, 5]
      

      您现在有了可以使用的非常通用的算法。例如:

      轻松转换(奇怪的)美国长度标准

      根据标准

      Unit Divisions
      1 foot 12 inches
      1 yard 3 feet
      1 mile 1760 yards
      > decompose(123_456, [1760 * 3 * 12, 3 * 12, 12])
      < [1, 1669, 1, 0]
      

      123456 英寸 = 1 英里、1669 码、1 英尺和 0 英寸

      或者您可以在一定程度上转换为十进制或二进制表示

      > decompose(123_456, [100_000, 10_000, 1000, 100, 10])
      < [1, 2, 3, 4, 5, 6]
      
      > decompose(127, [128, 64, 32, 16, 8, 4, 2])
      < [0, 1, 1, 1, 1, 1, 1, 1]
      

      也适用于浮点断点

      由于 Javascript 支持 mod 运算符与浮点数,你也可以这样做

      > decompose(26.5, [20, 2.5])
      < [1, 2, 1.5]
      

      没有断点的边缘情况也自然覆盖

      > decompose(123, [])
      < [123]
      

      【讨论】:

        【解决方案11】:

        这是 Number 类的扩展。 toHHMMSS() 将秒转换为 hh:mm:ss 字符串。

        Number.prototype.toHHMMSS = function() {
          var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600);
          var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2);
          var seconds = ("00" + (this % 3600) % 60).slice(-2);
          return hours + ":" + minutes + ":" + seconds;
        }
        
        // Usage: [number variable].toHHMMSS();
        
        // Here is a simple test
        var totalseconds = 1234;
        document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS();
        // HTML of the test
        <div id="timespan"></div>

        【讨论】:

          【解决方案12】:

          新手易于理解的版本:

           var totalNumberOfSeconds = YOURNUMBEROFSECONDS;
           var hours = parseInt( totalNumberOfSeconds / 3600 );
           var minutes = parseInt( (totalNumberOfSeconds - (hours * 3600)) / 60 );
           var seconds = Math.floor((totalNumberOfSeconds - ((hours * 3600) + (minutes * 60))));
           var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
           console.log(result);
          

          【讨论】:

            【解决方案13】:

            这个功能应该可以做到:

            var convertTime = function (input, separator) {
                var pad = function(input) {return input < 10 ? "0" + input : input;};
                return [
                    pad(Math.floor(input / 3600)),
                    pad(Math.floor(input % 3600 / 60)),
                    pad(Math.floor(input % 60)),
                ].join(typeof separator !== 'undefined' ?  separator : ':' );
            }
            

            不传递分隔符,它使用: 作为(默认)分隔符:

            time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51
            

            如果要使用-作为分隔符,只需将其作为第二个参数传递即可:

            time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46
            

            另见this Fiddle

            【讨论】:

            • 可以使用默认参数,例如 (input ,separator=":")。在我稍微修改它之前它也没有返回任何东西paste.ee/p/FDNag
            • @madprops :实际上,正如我已经解释的那样,我的答案中的版本已经将 : 设置为 separator 参数的默认值。这是由语句typeof separator !== 'undefined' ? separator : ':' 完成的。此外,您的功能与我的功能几乎相同,只是做了一些外观更改,它们都应该产生相同的输出......除了我的版本有更好的浏览器支持。您的将无法在任何版本的 Internet Explorer 或 MS Edge 中使用
            【解决方案14】:

            加入这个旧线程——OP 声明 HH:MM:SS,并且许多解决方案都有效,直到您意识到您需要列出超过 24 小时。也许您只需要一行代码。给你:

            d=(s)=>{f=Math.floor;g=(n)=>('00'+n).slice(-2);return f(s/3600)+':'+g(f(s/60)%60)+':'+g(s%60)}
            

            它返回 H+:MM:SS。要使用它,只需使用:

            d(91260);     // returns "25:21:00"
            d(960);       // returns "0:16:00"
            

            ...我试图让它使用尽可能少的代码,这是一种很好的单行方法。

            【讨论】:

            • 您能否提供您的代码的扩展/阅读版本,以便我们更容易看到发生了什么?谢谢。
            【解决方案15】:

            对于 HH:MM:SS.MS (eq: "00:04:33.637") 的特殊情况,FFMPEG 使用它来指定 毫秒

            [-][HH:]MM:SS[.m...]

            HH 表示小时数,MM 表示分钟数 最多 2 位,SS 秒数,最多 2 位数。末尾的 m 表示 SS 的十进制值。

            /* HH:MM:SS.MS to (FLOAT)seconds ---------------*/
            function timerToSec(timer){
               let vtimer = timer.split(":")
               let vhours = +vtimer[0]
               let vminutes = +vtimer[1]
               let vseconds = parseFloat(vtimer[2])
               return vhours * 3600 + vminutes * 60 + vseconds
            }
            
            /* Seconds to (STRING)HH:MM:SS.MS --------------*/
            function secToTimer(sec){
              let o = new Date(0)
              let p =  new Date(sec*1000)  
              return new Date(p.getTime()-o.getTime())
                .toISOString()
                .split("T")[1]
                .split("Z")[0]
            }
            
            /* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */
            const t = "07:04:33.637"
            console.log(
              t + " => " +
              timerToSec(t) +
              "s"
            )
            
            /* Test: 25473 seconds and 637 milliseconds */
            const s = 25473.637 // "25473.637"
            console.log(
              s + "s => " + 
              secToTimer(s)
            )

            示例用法,毫秒传输计时器:

            /* Seconds to (STRING)HH:MM:SS.MS --------------*/
            function secToTimer(sec){
              let o = new Date(0)
              let p =  new Date(sec*1000)  
              return new Date(p.getTime()-o.getTime())
                .toISOString()
                .split("T")[1]
                .split("Z")[0]
            }
            
            let job, origin = new Date().getTime()
            const timer = () => {
              job = requestAnimationFrame(timer)
              OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
            }
            
            requestAnimationFrame(timer)
            span {font-size:4rem}
            <span id="OUT"></span>
            <br>
            <button onclick="origin = new Date().getTime()">RESET</button>
            <button onclick="requestAnimationFrame(timer)">RESTART</button>
            <button onclick="cancelAnimationFrame(job)">STOP</button>

            示例用法,绑定到媒体元素

            /* Seconds to (STRING)HH:MM:SS.MS --------------*/
            function secToTimer(sec){
              let o = new Date(0)
              let p =  new Date(sec*1000)  
              return new Date(p.getTime()-o.getTime())
                .toISOString()
                .split("T")[1]
                .split("Z")[0]
            }
            
            VIDEO.addEventListener("timeupdate", function(e){
              OUT.textContent = secToTimer(e.target.currentTime)
            }, false)
            span {font-size:4rem}
            <span id="OUT"></span><br>
            <video id="VIDEO" width="400" controls autoplay>
              <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
            </video>

            题外话,那些用php写的函数:

            <?php 
            /* HH:MM:SS to (FLOAT)seconds ------------------*/
            function timerToSec($timer){
              $vtimer = explode(":",$timer);
              $vhours = (int)$vtimer[0];
              $vminutes = (int)$vtimer[1];
              $vseconds = (float)$vtimer[2];
              return $vhours * 3600 + $vminutes * 60 + $vseconds;
            }
            /* Seconds to (STRING)HH:MM:SS -----------------*/
            function secToTimer($sec){
              return explode(" ", date("H:i:s", $sec))[0];  
            }
            

            【讨论】:

            • 你可以省略+ "." + p.getMilliseconds(),只用new Date(p.getTime()-o.getTime()).toISOString().split("T")[1].split("Z")[0]
            • 看起来不错,是的,您的版本更快:参见基准jsben.ch/4sQY1 接受编辑!谢谢。
            【解决方案16】:

            在查看了所有答案并且对其中的大多数都不满意之后,这就是我想出的。我知道我的谈话很晚了,但无论如何都是这样。

            function secsToTime(secs){
              var time = new Date(); 
              // create Date object and set to today's date and time
              time.setHours(parseInt(secs/3600) % 24);
              time.setMinutes(parseInt(secs/60) % 60);
              time.setSeconds(parseInt(secs%60));
              time = time.toTimeString().split(" ")[0];
              // time.toString() = "HH:mm:ss GMT-0800 (PST)"
              // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
              // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
              return time;
            }
            

            我创建了一个新的 Date 对象,将时间更改为我的参数,将 Date 对象转换为时间字符串,并通过拆分字符串并仅返回需要的部分来删除其他内容。

            我想我会分享这种方法,因为它不需要正则表达式、逻辑和数学杂技来获得“HH:mm:ss”格式的结果,而是依赖于内置方法。

            您可能想在此处查看文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

            【讨论】:

              【解决方案17】:

              以下是将秒转换为 hh-mm-ss 格式的给定代码:

              var measuredTime = new Date(null);
              measuredTime.setSeconds(4995); // specify value of SECONDS
              var MHSTime = measuredTime.toISOString().substr(11, 8);
              

              Convert seconds to HH-MM-SS format in JavaScript获取替代方法

              【讨论】:

              【解决方案18】:
              var time1 = date1.getTime();
              var time2 = date2.getTime();
              var totalMilisec = time2 - time1;
              
              alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))
              
               /* ----------------------------------------------------------
               *  Field        | Full Form          | Short Form
               *  -------------|--------------------|-----------------------
               *  Year         | yyyy (4 digits)    | yy (2 digits)
               *  Month        | MMM (abbr.)        | MM (2 digits)
                               | NNN (name)         |
               *  Day of Month | dd (2 digits)      | 
               *  Day of Week  | EE (name)          | E (abbr)
               *  Hour (1-12)  | hh (2 digits)      | 
               *  Minute       | mm (2 digits)      | 
               *  Second       | ss (2 digits)      | 
               *  ----------------------------------------------------------
               */
              function DateFormat(formatString,date){
                  if (typeof date=='undefined'){
                  var DateToFormat=new Date();
                  }
                  else{
                      var DateToFormat=date;
                  }
                  var DAY         = DateToFormat.getDate();
                  var DAYidx      = DateToFormat.getDay();
                  var MONTH       = DateToFormat.getMonth()+1;
                  var MONTHidx    = DateToFormat.getMonth();
                  var YEAR        = DateToFormat.getYear();
                  var FULL_YEAR   = DateToFormat.getFullYear();
                  var HOUR        = DateToFormat.getHours();
                  var MINUTES     = DateToFormat.getMinutes();
                  var SECONDS     = DateToFormat.getSeconds();
              
                  var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
                  var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
                  var strMONTH;
                  var strDAY;
                  var strHOUR;
                  var strMINUTES;
                  var strSECONDS;
                  var Separator;
              
                  if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
                      strMONTH = "0" + MONTH;
                  else
                      strMONTH=MONTH;
                  if(parseInt(DAY)< 10 && DAY.toString().length < 2)
                      strDAY = "0" + DAY;
                  else
                      strDAY=DAY;
                  if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
                      strHOUR = "0" + HOUR;
                  else
                      strHOUR=HOUR;
                  if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
                      strMINUTES = "0" + MINUTES;
                  else
                      strMINUTES=MINUTES;
                  if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
                      strSECONDS = "0" + SECONDS;
                  else
                      strSECONDS=SECONDS;
              
                  switch (formatString){
                      case "hh:mm:ss":
                          return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
                      break;
                      //More cases to meet your requirements.
                  }
              }
              

              【讨论】:

                【解决方案19】:

                我只是想对上面的好答案做一点解释:

                var totalSec = new Date().getTime() / 1000;
                var hours = parseInt( totalSec / 3600 ) % 24;
                var minutes = parseInt( totalSec / 60 ) % 60;
                var seconds = totalSec % 60;
                
                var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);
                

                在第二行,由于 1 小时有 3600 秒,我们将总秒数除以 3600 得到总小时数。我们使用 parseInt 去除任何小数。如果 totalSec 为 12600(3 个半小时),则 parseInt(totalSec / 3600) 将返回 3,因为我们将有 3 个完整小时。在这种情况下,为什么我们需要 % 24 ?如果我们超过 24 小时,假设我们有 25 小时(90000 秒),那么这里的模数将使我们再次回到 1,而不是返回 25。它将结果限制在 24 小时限制内,因为有 24 小时一天内。

                当你看到这样的东西时:

                25 % 24
                

                这样想:

                25 mod 24 or what is the remainder when we divide 25 by 24
                

                【讨论】:

                  【解决方案20】:

                  这是一个根据 powtac 的回答 here 将秒转换为 hh-mm-ss 格式的函数

                  jsfiddle

                  /** 
                   * Convert seconds to hh-mm-ss format.
                   * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
                  **/
                  var SecondsTohhmmss = function(totalSeconds) {
                    var hours   = Math.floor(totalSeconds / 3600);
                    var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
                    var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
                  
                    // round seconds
                    seconds = Math.round(seconds * 100) / 100
                  
                    var result = (hours < 10 ? "0" + hours : hours);
                        result += "-" + (minutes < 10 ? "0" + minutes : minutes);
                        result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
                    return result;
                  }
                  

                  示例使用

                  var seconds = SecondsTohhmmss(70);
                  console.log(seconds);
                  // logs 00-01-10
                  

                  【讨论】:

                    【解决方案21】:

                    有很多解决这个问题的选项,显然有很好的选项建议,但是我想在这里添加一个更优化的代码

                    function formatSeconds(sec) {
                         return [(sec / 3600), ((sec % 3600) / 60), ((sec % 3600) % 60)]
                                .map(v => v < 10 ? "0" + parseInt(v) : parseInt(v))
                                .filter((i, j) => i !== "00" || j > 0)
                                .join(":");
                    }
                    

                    如果你不想用小于 10 的数字格式化零,你可以使用

                    function formatSeconds(sec) {
                      return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);
                    

                    }

                    示例代码http://fiddly.org/1c476/1

                    【讨论】:

                      【解决方案22】:

                      在一行中,使用 T.J.克劳德的解决方案:

                      secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`
                      

                      在一行中,另一种也计算天数的解决方案:

                      secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`
                      

                      来源:https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

                      【讨论】:

                        【解决方案23】:
                        var sec_to_hms = function(sec){
                        var min, hours;
                             sec = sec - (min = Math.floor(sec/60))*60;
                             min = min - (hours = Math.floor(min/60))*60;
                             return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
                        }
                        alert(sec_to_hms(2442542));
                        

                        【讨论】:

                          【解决方案24】:

                          这里没有一个答案能满足我的要求,因为我希望能够处理

                          1. 大量秒(天),并且
                          2. 负数

                          尽管 OP 不要求这些,但最好的做法是覆盖边缘情况,尤其是在不费吹灰之力的情况下。

                          很明显,当他说 seconds 时,OP 的意思是 NUMBER 秒。为什么要将您的功能与String 挂钩?

                          function secondsToTimeSpan(seconds) {
                              const value = Math.abs(seconds);
                              const days = Math.floor(value / 1440);
                              const hours = Math.floor((value - (days * 1440)) / 3600);
                              const min = Math.floor((value - (days * 1440) - (hours * 3600)) / 60);
                              const sec = value - (days * 1440) - (hours * 3600) - (min * 60);
                              return `${seconds < 0 ? '-':''}${days > 0 ? days + '.':''}${hours < 10 ? '0' + hours:hours}:${min < 10 ? '0' + min:min}:${sec < 10 ? '0' + sec:sec}`
                          }
                          secondsToTimeSpan(0);       // => 00:00:00
                          secondsToTimeSpan(1);       // => 00:00:01
                          secondsToTimeSpan(1440);    // => 1.00:00:00
                          secondsToTimeSpan(-1440);   // => -1.00:00:00
                          secondsToTimeSpan(-1);      // => -00:00:01
                          

                          【讨论】:

                          • secondsToTimeSpan(8991) 返回6.00:05:51 而我认为它应该返回00:02:29:51
                          【解决方案25】:

                          您是否尝试过向 Date 对象添加秒数?

                          Date.prototype.addSeconds = function(seconds) {
                              this.setSeconds(this.getSeconds() + seconds);
                          };
                          var dt = new Date();
                          dt.addSeconds(1234);
                          

                          一个样本: https://jsfiddle.net/j5g2p0dc/5/

                          更新: 示例链接丢失,因此我创建了一个新链接。

                          【讨论】:

                          • 未捕获的类型错误:dt.addSeconds 不是函数
                          • @Ikrom 检查示例,我在 jsfiddle 中创建了一个新的,因为旧的返回 404 错误
                          • 看起来我没有发布你在日期对象上使用自定义方法addSeconds,比如Date.prototype.addSeconds = function(seconds){...}。是的,它有效,感谢您的更新。
                          【解决方案26】:

                          将秒转换为 hh:mm:ss 格式的简单函数:

                          function getHHMMSSFromSeconds(totalSeconds) {
                              if (!totalSeconds) {
                                return '00:00:00';
                              }
                              const hours = Math.floor(totalSeconds / 3600);
                              const minutes = Math.floor(totalSeconds % 3600 / 60);
                              const seconds = totalSeconds % 60;
                              const hhmmss = padTo2(hours) + ':' + padTo2(minutes) + ':' + padTo2(seconds);
                              return hhmmss;
                          }
                          
                          // function to convert single digit to double digit
                          function padTo2(value) {
                              if (!value) {
                                return '00';
                              }
                              return value < 10 ? String(value).padStart(2, '0') : value;
                          }
                          

                          【讨论】:

                            【解决方案27】:

                            您也可以使用以下代码:

                            int ss = nDur%60;
                            nDur   = nDur/60;
                            int mm = nDur%60;
                            int hh = nDur/60;
                            

                            【讨论】:

                              【解决方案28】:

                              对于任何使用 AngularJS 的人,一个简单的解决方案是使用 date API 过滤值,它根据请求的格式将毫秒转换为字符串。示例:

                              <div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
                              

                              请注意,这需要毫秒,因此如果您要从秒转换(正如原始问题所制定的那样),您可能需要将 timeRemaining 乘以 1000。

                              【讨论】:

                                【解决方案29】:

                                我遇到了一些人提到的秒数超过一天的情况。这是@Harish Anchu 的最高评价答案的改编版本,它占了更长的时间:

                                function secondsToTime(seconds) {
                                  const arr = new Date(seconds * 1000).toISOString().substr(11, 8).split(':');
                                
                                  const days = Math.floor(seconds / 86400);
                                  arr[0] = parseInt(arr[0], 10) + days * 24;
                                
                                  return arr.join(':');
                                }
                                

                                例子:

                                secondsToTime(101596) // outputs '28:13:16' as opposed to '04:13:16'
                                

                                【讨论】:

                                  【解决方案30】:
                                  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;
                                  }
                                  

                                  使用示例

                                  alert("186".toHHMMSS());
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2018-11-08
                                    • 2013-07-22
                                    • 1970-01-01
                                    • 2020-05-10
                                    相关资源
                                    最近更新 更多