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


当前回答

我认为标准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);

其他回答

这招很管用:

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;
}

(来源此处)

已经有很多答案了,但我的要求是:

转换为持续时间(即,应适用于大于24小时的值) 关心的小数秒到给定的十进制精度 如果为零,则截断前面的小时和分钟。

const seconds2duration = ( seconds, decimals=0 ) => { let fraction = ( seconds - Math.floor( seconds ) ).toFixed( decimals ); fraction = decimals === 0 ? '' : fraction.slice( 1 ); const [ hours, mins, secs ] = [ seconds / 3600, seconds % 3600 / 60, seconds % 3600 % 60 ].map( ( x ) => String( Math.floor( x ) ).padStart( 2, '0' ) ); if ( hours === '00' && mins === '00' ) { return secs + fraction; } else if ( hours === '00' ) { return [ mins, secs + fraction ].join( ':' ); } else { return [ hours, mins, secs + fraction ].join( ':' ); } }; console.log(seconds2duration(25*3600 + 0*60 + 41 + 0.333, 0)); // 25:00:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 0)); // 05:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 1)); // 05:41.3 console.log(seconds2duration(0*3600 + 0*60 + 41 + 0.333, 2)); // 41.33

试试这个:

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

当我想象一个时钟或计时器时,我会这样做:

const secondsTo_HHMMSS = (seconds) => {
      //format to a readable friendly timer
      let hour = Math.floor(seconds / 3600);
      let minute = Math.floor((seconds % 3600) / 60);
      let second = seconds % 60;

      if(hour.toString().length === 1) {
            hour = `0${hour}`;
      }
      if(minute.toString().length === 1) {
            minute = `0${minute}`;
      }
      if(second.toString().length === 1) {
            second = `0${second}`;
      };

      let timer = `${hour}-${minute}-${second}`;

      return timer;
}

再来看看这个老话题——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"

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