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


当前回答

这是一个非常简单的任务,但你们中的一些人直接推荐了Moment.js,或者创建了一些最丑陋的函数来解析一些秒…

transform(time: number): string {
    if (time != null) {
        const hours: number = Math.floor(time / 3600);
        const minutes: number = Math.floor((time - (hours * 3600)) / 60);
        const seconds: number = time - (hours * 3600) - (minutes * 60);
        return [hours, (minutes < 10) ? '0' + minutes : minutes, (seconds < 10) ? '0' + seconds : seconds].join(':');
    } else {
        return '00:00:00';
    }
}

这在任何情况下都适用……

其他回答

我遇到了一些人提到的情况,其中秒的数量超过了一天。以下是@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'

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

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

这是一个非常简单的任务,但你们中的一些人直接推荐了Moment.js,或者创建了一些最丑陋的函数来解析一些秒…

transform(time: number): string {
    if (time != null) {
        const hours: number = Math.floor(time / 3600);
        const minutes: number = Math.floor((time - (hours * 3600)) / 60);
        const seconds: number = time - (hours * 3600) - (minutes * 60);
        return [hours, (minutes < 10) ? '0' + minutes : minutes, (seconds < 10) ? '0' + seconds : seconds].join(':');
    } else {
        return '00:00:00';
    }
}

这在任何情况下都适用……

易于遵循的版本为菜鸟:

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