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


当前回答

易于遵循的版本为菜鸟:

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

其他回答

在一行中,使用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

正如Cleiton在他的回答中指出的,moment.js可以用于:

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

试试这个:

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

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

大量的秒(天),以及 负数

尽管OP不要求这些,但是覆盖边缘情况是一个很好的实践,特别是当它不需要花费太多精力时。

很明显,当他说秒的时候,OP的意思是秒的数量。为什么要把函数固定在字符串上?

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

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

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