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


当前回答

我只是想对上面这个不错的答案做一点解释:

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

On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.

当你看到这样的东西:

25 % 24

你可以这样想:

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

其他回答

export const secondsToHHMMSS = (seconds) => {
  const HH = `${Math.floor(seconds / 3600)}`.padStart(2, '0');
  const MM = `${Math.floor(seconds / 60) % 60}`.padStart(2, '0');
  const SS = `${Math.floor(seconds % 60)}`.padStart(2, '0');
  return [HH, MM, SS].join(':');
};

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

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

请注意,这需要毫秒,所以如果从秒转换(就像最初的问题一样),可能需要将timerremain乘以1000。

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

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(":");
}

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

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

}

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

一个好的选择是使用Intl.DateTimeFormat。例子:

const timeFormat = new Intl.DateTimeFormat('es-US', {
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
    hour12: false,
    timeZone: 'UTC'
});

const endTimeFormatted = timeFormat.format(new Date(SECS * 1000); //hour in secs

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

[-] [HH: MM: SS(打烊……) 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];  
}