How to convert seconds to HH:mm:ss in moment.js

前端 未结 1 1611
栀梦
栀梦 2020-12-04 10:59

How can I convert seconds to HH:mm:ss?

At the moment I am using the function below

render: function (data){
     return new Date(data*10         


        
相关标签:
1条回答
  • 2020-12-04 11:01

    From this post I would try this to avoid leap issues

    moment("2015-01-01").startOf('day')
        .seconds(s)
        .format('H:mm:ss');
    

    I did not run jsPerf, but I would think this is faster than creating new date objects a million times

    function pad(num) {
        return ("0"+num).slice(-2);
    }
    function hhmmss(secs) {
      var minutes = Math.floor(secs / 60);
      secs = secs%60;
      var hours = Math.floor(minutes/60)
      minutes = minutes%60;
      return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
      // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
    }
    

    function pad(num) {
        return ("0"+num).slice(-2);
    }
    function hhmmss(secs) {
      var minutes = Math.floor(secs / 60);
      secs = secs%60;
      var hours = Math.floor(minutes/60)
      minutes = minutes%60;
      return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
      // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
    }
    
    for (var i=60;i<=60*60*5;i++) {
     document.write(hhmmss(i)+'<br/>');
    }
    
    
    /* 
    function show(s) {
      var d = new Date();
      var d1 = new Date(d.getTime()+s*1000);
      var  hms = hhmmss(s);
      return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
    }    
    */

    0 讨论(0)
提交回复
热议问题