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


当前回答

您可以使用ES6生成器创建高度可定制的时间字符串。

下面是将数字从给定比例转换为数组的通用函数:

函数toScaledArray (n,尺度){ 函数* g(x, n=0){ 如果(x > 0) { 产生x %(尺度[n] | |∞); 产量* g (Math.floor (x /鳞片[n]), n + 1) } } 返回g (n)[…] } console.log (toScaledArray (6 (10,10))) console.log (toScaledArray(2000年,[30,12])) console.log (toScaledArray(45000年,[12]24日30日))

因此,我们可以使用它来创建时间字符串,如下所示:

> toScaledArray(45000,[60,60]).reverse().join(":")
< '12:30:0'
> toScaledArray(1234,[60,60]).reverse().join(":")
< '20:34'

函数也可以写成一行:

[...(function* g(x,n=0,scales=[60,60]){if(x>0) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().join("-")

上面的函数将省略前导零,如果你想将字符串精确地转换为'HH-MM-SS',你可以使用

[...(function* g(x,n=0,scales=[60,60]){if(x>0||n<3) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().map(x=>String(x).padStart(2, '0')).join("-")

此外,如果你需要的是'[H:]MM:SS',这里我们有:

Number.prototype.toTimeString = function(){ 返回[…(*函数g (x, n = 0,鳞片= (60 60)){if (x > 0 | | n < 2){收益率x %(尺度[n] | |∞);产量* g (Math.floor (x /鳞片[n]), n + 1,尺度)}})(这)]. map ((x, n) = > n < 2 ?字符串(x) .padStart (2, ' 0 '): x) .reverse () . join(“:”) } console.log (12 (12) .toTimeString ()) console.log (345, (345) .toTimeString ()) console.log (6789, (6789) .toTimeString ())

你也可以有D(ay),甚至M(onth)和Y(ear)(虽然不准确),如下所示:

> toScaledArray(123456789,[60,60,24,30,12]).map((x,n)=>n<2?String(x).padStart(2,'0'):x).reverse().join(":")
< '3:11:18:21:33:09'

这里输出的意思是“3年11个月18天21小时33分9秒”

总之,这是一种高度可定制的将数字转换为可缩放数组的方法,可用于时间字符串转换、人类可读的字节转换甚至纸币的更改。

其他回答

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

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

易于遵循的版本为菜鸟:

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

更新(2020):

请使用@Frank的一句话解决方案:

new Date(SECONDS * 1000).toISOString().substring(11, 16)

如果SECONDS<3600并且你只想显示MM:SS,那么使用下面的代码:

new Date(SECONDS * 1000).toISOString().substring(14, 19)

这是目前为止最好的解决办法。


旧的回答:

使用Moment.js库。

var  timeInSec = "661"; //even it can be string

String.prototype.toHHMMSS = function () { 
   /* extend the String by using prototypical inheritance */
    var seconds = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    seconds = seconds - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
}

alert("5678".toHHMMSS());   // "01:34:38"
console.log(timeInSec.toHHMMSS());   //"00:11:01"

我们可以把这个函数写得更短更清晰,但这会降低可读性,所以我们要把它写得尽可能简单,尽可能稳定。

或者你可以在这里检查一下:

在JavaScript Date方法的帮助下,你可以在没有任何外部JavaScript库的情况下做到这一点,如下:

const date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
const result = date.toISOString().slice(11, 19);

或者,按照@Frank的评论;一句话:

new Date(SECONDS * 1000).toISOString().slice(11, 19);