使用 JavaScript 将秒转换为 HH-MM-SS?

发布于 2025-01-03 10:14:44 字数 55 浏览 1 评论 0 原文

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

How can I convert seconds to an HH-MM-SS string using JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

疧_╮線 2025-01-10 10:14:45

您是否尝试过向 Date 对象添加秒?

Date.prototype.addSeconds = function(seconds) {
    this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);

样本:
https://jsfiddle.net/j5g2p0dc/5/

更新:
示例链接丢失,因此我创建了一个新链接。

Have you tried adding seconds to a Date object?

Date.prototype.addSeconds = function(seconds) {
    this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);

A sample:
https://jsfiddle.net/j5g2p0dc/5/

Updated:
Sample link was missing so I created a new one.

十二 2025-01-10 10:14:45

您还可以使用下面的代码:

int ss = nDur%60;
nDur   = nDur/60;
int mm = nDur%60;
int hh = nDur/60;

You can also use below code:

int ss = nDur%60;
nDur   = nDur/60;
int mm = nDur%60;
int hh = nDur/60;
这个俗人 2025-01-10 10:14:45

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

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

请注意,这需要毫秒,因此如果您要从秒转换(如原始问题的表述),您可能需要将 timeRemaining 乘以 1000。

For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:

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

Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).

灼痛 2025-01-10 10:14:44

您可以借助 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);

You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:

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

Or, as per @Frank's comment; a one liner:

new Date(SECONDS * 1000).toISOString().slice(11, 19);
昵称有卵用 2025-01-10 10:14:44

更新(2020):

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

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

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

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

这是迄今为止最好的解决方案。


旧答案:

使用Moment.js库。

Updated (2020):

Please use @Frank's one line solution:

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

If SECONDS<3600 and if you want to show only MM:SS then use below code:

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

It is by far the best solution.


Old answer:

Use the Moment.js library.

沙沙粒小 2025-01-10 10:14:44

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

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

Example:

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

故人爱我别走 2025-01-10 10:14:44

我知道这有点旧,但是......

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}

它将输出:

toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18

I know this is kinda old, but...

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}

It will output:

toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18
宛菡 2025-01-10 10:14:44

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

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

As Cleiton pointed out in his answer, moment.js can be used for this:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');
爺獨霸怡葒院 2025-01-10 10:14:44

这是一个转换时间的简单函数,可能会有所帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

Here's a simple function for converting times that might help

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
自由范儿 2025-01-10 10:14:44

这可以解决问题:(

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

源自此处

This does the trick:

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

(Sourced from here)

江南烟雨〆相思醉 2025-01-10 10:14:44
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"

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

或者您可以在此处检查此工作:

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"

we can make this function lot shorter and crisp but that decreases the readability, so we will write it as simple as possible and as stable as possible.

or you can check this working here:

懷念過去 2025-01-10 10:14:44

我认为最通用(且神秘)的解决方案可能是这个

function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (pipeline, breakpoint) => remainder =>
        [Math.floor(remainder / breakpoint)].concat(pipeline(remainder % breakpoint)),
      r => [r]
    )(seconds)
    .map(amount => amount.toString().padStart(2, '0'))
    .join('-');
}

或者复制并复制粘贴最短的版本

function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
      r => [r]
    )(seconds)
    .map(a => a.toString().padStart(2, '0'))
    .join('-');
}

一些示例输出:

> hms(0)
< "00-00-00"

> hms(5)
< "00-00-05"

> hms(60)
< "00-01-00"

> hms(3785)
< "01-03-05"

> hms(37850)
< "10-30-50"

> hms(378500)
< "105-08-20"

工作原理

算法

  1. 要获得小时数,请将总秒数除以 3600 并将其取整。
  2. 要获得分钟数,请将余数除以 60 并将其取整。
  3. 要获得秒数,只需使用余数即可。

将各个金额保存在数组中以便于格式化也很好。

例如,输入 3785 秒,输出应为 [1, 3, 5],即 1 小时 3 分 5 秒。

创建管道

将 3600 和 60 常量命名为“断点”,您可以将此算法写入函数,因为

function divideAndAppend(remainder, breakpoint, callback) {
  return [Math.floor(remainder / breakpoint)].concat(callback(remainder % breakpoint));
}

它返回一个数组,其中第一项是给定断点的数量,数组的其余部分由回调给出。
在回调函数中重用 divideAndAppend 将为您提供一个组合管道 divideAndAppend 函数。其中每一项
计算每个给定断点的数量并将其附加到数组中以生成所需的输出。

然后,您还需要结束该管道的“最终”回调。换句话说,您使用了所有断点,现在只剩下剩余的断点。
由于您已经在 3) 处得到了答案,因此您应该使用某种恒等函数,在本例中 remainder => [余数]

您现在可以像这样编写管道了,

let pipeline = r3 => divideAndAppend(
    r3, 
    3600, 
    r2 => divideAndAppend(
        r2, 
        60, 
        r1 => [r1]));

> pipeline(3785)
< [1, 3, 5]

很酷吗?

使用 for 循环进行泛化

现​​在,您可以使用可变数量的断点进行泛化,并创建一个 for 循环,将各个 divideAndAppend 函数组合成
管道。
您从恒等函数 r1 => 开始[r1],然后使用 60 断点,最后使用 3600 断点。

let breakpoints = [60, 3600];
let pipeline = r => [r];

for (const b of breakpoints) {
  const previousPipeline = pipeline;
  pipeline = r => divideAndAppend(r, b, previousPipeline);
}

> pipeline(3785)
< [1, 3, 5]

使用 Array.prototype.reduce()

现在您可以将这个 for 循环重写为 reducer,以获得更短、更实用的代码。换句话说,将函数组合重写到reducer 中。

let pipeline = [60, 3600].reduce(
  (ppln, b) => r => divideAndAppend(r, b, ppln),
  r => [r]
);

> pipeline(3785)
< [1, 3, 5]

累加器 ppln 是管道,您正在使用它的早期版本来编写它。初始管道是 r =>; [r]。

您现在可以内联函数 divideAndAppend 并使用 Array.prototype.reduceRight ,它与 [].reverse().reduce(...)< /code> 来设置断点
定义更加自然。

let pipeline = [3600, 60]
    .reduceRight(
      (ppln, b) => r => [Math.floor(r / b)].concat(ppln(r % b)),
      r => [r]
    );

这是最终的形式。然后,您只需应用映射到左侧填充 0 的字符串,并使用 : 分隔符连接字符串;

更多泛化

将减速器包装到函数中,

function decompose(total, breakpoints) {
  return breakpoints.reduceRight(
    (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
    r => [r]
  )(total);
}

> decompose(3785, [3600, 60])
< [1, 3, 5]

您现在可以使用非常通用的算法。例如:

轻松转换(奇怪的)美国长度标准

给定标准

单位 划分
1 英尺 12 英寸
1 码 3 英尺
1 英里 1760 码
> decompose(123_456, [1760 * 3 * 12, 3 * 12, 12])
< [1, 1669, 1, 0]

123456 英寸 = 1 英里、1669 码、1 英尺和 0 英寸

或者您可以转换为十进制或二进制表示

> decompose(123_456, [100_000, 10_000, 1000, 100, 10])
< [1, 2, 3, 4, 5, 6]

> decompose(127, [128, 64, 32, 16, 8, 4, 2])
< [0, 1, 1, 1, 1, 1, 1, 1]

也适用于浮点断点

由于Javascript支持带有浮点数的mod运算符,因此您还可以执行

> decompose(26.5, [20, 2.5])
< [1, 2, 1.5]

no的边缘情况断点也自然被覆盖

> decompose(123, [])
< [123]

I think the most general (and cryptic) solution could be this

function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (pipeline, breakpoint) => remainder =>
        [Math.floor(remainder / breakpoint)].concat(pipeline(remainder % breakpoint)),
      r => [r]
    )(seconds)
    .map(amount => amount.toString().padStart(2, '0'))
    .join('-');
}

Or to copy & paste the shortest version

function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
      r => [r]
    )(seconds)
    .map(a => a.toString().padStart(2, '0'))
    .join('-');
}

Some example outputs:

> hms(0)
< "00-00-00"

> hms(5)
< "00-00-05"

> hms(60)
< "00-01-00"

> hms(3785)
< "01-03-05"

> hms(37850)
< "10-30-50"

> hms(378500)
< "105-08-20"

How it works

Algorithm

  1. To get hours you divide total seconds by 3600 and floor it.
  2. To get minutes you divide remainder by 60 and floor it.
  3. To get seconds you just use the remainder.

It would also be nice to keep individual amounts in an array for easier formatting.

For example given the input of 3785s the output should be [1, 3, 5], that is 1 hour, 3 minutes and 5 seconds.

Creating pipeline

Naming the 3600 and 60 constants "breakpoints" you can write this algorithm into function as this

function divideAndAppend(remainder, breakpoint, callback) {
  return [Math.floor(remainder / breakpoint)].concat(callback(remainder % breakpoint));
}

It returns an array where first item is the amount for given breakpoint and the rest of the array is given by the callback.
Reusing the divideAndAppend in callback function will give you a pipeline of composed divideAndAppend functions. Each one of these
computes amount per given breakpoint and append it to the array making your desired output.

Then you also need the "final" callback that ends this pipeline. In another words you used all breakpoints and now you have only the remainder.
Since you have already the answer at 3) you should use some sort of identity function, in this case remainder => [remainder].

You can now write the pipeline like this

let pipeline = r3 => divideAndAppend(
    r3, 
    3600, 
    r2 => divideAndAppend(
        r2, 
        60, 
        r1 => [r1]));

> pipeline(3785)
< [1, 3, 5]

Cool right?

Generalizing using for-loop

Now you can generalize with a variable amount of breakpoints and create a for-loop that will compose individial divideAndAppend functions into
the pipeline.
You start with the identity function r1 => [r1], then use the 60 breakpoint and finally use the 3600 breakpoint.

let breakpoints = [60, 3600];
let pipeline = r => [r];

for (const b of breakpoints) {
  const previousPipeline = pipeline;
  pipeline = r => divideAndAppend(r, b, previousPipeline);
}

> pipeline(3785)
< [1, 3, 5]

Using Array.prototype.reduce()

Now you can rewrite this for-loop into reducer for shorter and more functional code. In other words rewrite function composition into the reducer.

let pipeline = [60, 3600].reduce(
  (ppln, b) => r => divideAndAppend(r, b, ppln),
  r => [r]
);

> pipeline(3785)
< [1, 3, 5]

The accumulator ppln is the pipeline and you are composing it using the previous version of it. The initial pipeline is r => [r].

You can now inline the function divideAndAppend and use Array.prototype.reduceRight which is the same as [].reverse().reduce(...) to make the breakpoints
definitions more natural.

let pipeline = [3600, 60]
    .reduceRight(
      (ppln, b) => r => [Math.floor(r / b)].concat(ppln(r % b)),
      r => [r]
    );

Which is the final form. Then you just appy mapping to string with padded 0's on left and join the strings with : separator;

More generalizations

Wrapping the reducer into function

function decompose(total, breakpoints) {
  return breakpoints.reduceRight(
    (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
    r => [r]
  )(total);
}

> decompose(3785, [3600, 60])
< [1, 3, 5]

you now have very general algorithm you can work with. For example:

Convert easily (the weird) us length standards

Given the standards

Unit Divisions
1 foot 12 inches
1 yard 3 feet
1 mile 1760 yards
> decompose(123_456, [1760 * 3 * 12, 3 * 12, 12])
< [1, 1669, 1, 0]

123456 in = 1 mi, 1669 yd, 1 feet and 0 in

Or you can somewhat convert to decimal or binary representations

> decompose(123_456, [100_000, 10_000, 1000, 100, 10])
< [1, 2, 3, 4, 5, 6]

> decompose(127, [128, 64, 32, 16, 8, 4, 2])
< [0, 1, 1, 1, 1, 1, 1, 1]

Works also with floating point breakpoints

Since Javascript supports mod operator with floating point numbers, you can also do

> decompose(26.5, [20, 2.5])
< [1, 2, 1.5]

The edge case of no breakpoints is also naturally covered

> decompose(123, [])
< [123]
少女情怀诗 2025-01-10 10:14:44

试试这个:

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

Try this:

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
辞慾 2025-01-10 10:14:44

这是 Number 类的扩展。 toHHMMSS() 将秒转换为 hh:mm:ss 字符串。

Number.prototype.toHHMMSS = function() {
  var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600);
  var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2);
  var seconds = ("00" + (this % 3600) % 60).slice(-2);
  return hours + ":" + minutes + ":" + seconds;
}

// Usage: [number variable].toHHMMSS();

// Here is a simple test
var totalseconds = 1234;
document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS();
// HTML of the test
<div id="timespan"></div>

Here is an extension to Number class. toHHMMSS() converts seconds to an hh:mm:ss string.

Number.prototype.toHHMMSS = function() {
  var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600);
  var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2);
  var seconds = ("00" + (this % 3600) % 60).slice(-2);
  return hours + ":" + minutes + ":" + seconds;
}

// Usage: [number variable].toHHMMSS();

// Here is a simple test
var totalseconds = 1234;
document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS();
// HTML of the test
<div id="timespan"></div>

烂人 2025-01-10 10:14:44

适合新手的易于理解的版本:

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

Easy to follow version for noobies:

 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);
不如归去 2025-01-10 10:14:44

这个函数应该做到这一点:

var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

在不传递分隔符的情况下,它使用 : 作为(默认)分隔符:

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

如果您想使用 - 作为分隔符,只需将其作为第二个参数:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

另请参阅这个Fiddle

This function should do it :

var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

Without passing a separator, it uses : as the (default) separator :

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

If you want to use - as a separator, just pass it as the second parameter:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

See also this Fiddle.

笑红尘 2025-01-10 10:14:44

插话这个旧线程 - 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"

...我试图让它使用尽可能少的代码,以获得一种很好的单行方法。

Chiming in on this old thread -- the OP stated HH:MM:SS, and many of the solutions work, until you realize you need more than 24 hours listed. And maybe you don't want more than a single line of code. Here you go:

d=(s)=>{f=Math.floor;g=(n)=>('00'+n).slice(-2);return f(s/3600)+':'+g(f(s/60)%60)+':'+g(s%60)}

It returns H+:MM:SS. To use it, simply use:

d(91260);     // returns "25:21:00"
d(960);       // returns "0:16:00"

...I tried to get it to use the least amount of code possible, for a nice one-liner approach.

月隐月明月朦胧 2025-01-10 10:14:44

在查看了所有答案并对其中大多数答案不满意之后,这就是我想到的。我知道我已经很晚才开始谈话,但无论如何,事情就在这里。

function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}

我创建一个新的 Date 对象,将时间更改为参数,将 Date 对象转换为时间字符串,并通过拆分字符串并仅返回需要的部分来删除附加内容。

我想我会分享这种方法,因为它不需要正则表达式、逻辑和数学杂技来获得“HH:mm:ss”格式的结果,而是依赖于内置方法。

您可能需要查看此处的文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}

I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

风吹短裙飘 2025-01-10 10:14:44

对于HH:MM:SS.MS(eq:“00:04:33.637”)的特殊情况。 html#time-duration-syntax" rel="nofollow noreferrer">FFMPEG 指定毫秒

[-][HH:]MM:SS[.m...]

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

For the special case of HH:MM:SS.MS (eq: "00:04:33.637") as used by FFMPEG to specify milliseconds.

[-][HH:]MM:SS[.m...]

HH expresses the number of hours, MM the number of minutes for a
maximum of 2 digits, and SS the number of seconds for a maximum of 2
digits. The m at the end expresses decimal value for 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)
)

Example usage, a milliseconds transport timer:

/* 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>

Example usage, binded to a media element

/* 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>


Outside the question, those functions written in 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];  
}
夜清冷一曲。 2025-01-10 10:14:44

将秒转换为 hh:mm:ss 格式的简单函数:

function getHHMMSSFromSeconds(totalSeconds) {
    if (!totalSeconds) {
      return '00:00:00';
    }
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor(totalSeconds % 3600 / 60);
    const seconds = totalSeconds % 60;
    const hhmmss = padTo2(hours) + ':' + padTo2(minutes) + ':' + padTo2(seconds);
    return hhmmss;
}

// function to convert single digit to double digit
function padTo2(value) {
    if (!value) {
      return '00';
    }
    return value < 10 ? String(value).padStart(2, '0') : value;
}

Simple function to convert seconds into in hh:mm:ss format :

function getHHMMSSFromSeconds(totalSeconds) {
    if (!totalSeconds) {
      return '00:00:00';
    }
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor(totalSeconds % 3600 / 60);
    const seconds = totalSeconds % 60;
    const hhmmss = padTo2(hours) + ':' + padTo2(minutes) + ':' + padTo2(seconds);
    return hhmmss;
}

// function to convert single digit to double digit
function padTo2(value) {
    if (!value) {
      return '00';
    }
    return value < 10 ? String(value).padStart(2, '0') : value;
}
一世旳自豪 2025-01-10 10:14:44
var time1 = date1.getTime();
var time2 = date2.getTime();
var totalMilisec = time2 - time1;

alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))

 /* ----------------------------------------------------------
 *  Field        | Full Form          | Short Form
 *  -------------|--------------------|-----------------------
 *  Year         | yyyy (4 digits)    | yy (2 digits)
 *  Month        | MMM (abbr.)        | MM (2 digits)
                 | NNN (name)         |
 *  Day of Month | dd (2 digits)      | 
 *  Day of Week  | EE (name)          | E (abbr)
 *  Hour (1-12)  | hh (2 digits)      | 
 *  Minute       | mm (2 digits)      | 
 *  Second       | ss (2 digits)      | 
 *  ----------------------------------------------------------
 */
function DateFormat(formatString,date){
    if (typeof date=='undefined'){
    var DateToFormat=new Date();
    }
    else{
        var DateToFormat=date;
    }
    var DAY         = DateToFormat.getDate();
    var DAYidx      = DateToFormat.getDay();
    var MONTH       = DateToFormat.getMonth()+1;
    var MONTHidx    = DateToFormat.getMonth();
    var YEAR        = DateToFormat.getYear();
    var FULL_YEAR   = DateToFormat.getFullYear();
    var HOUR        = DateToFormat.getHours();
    var MINUTES     = DateToFormat.getMinutes();
    var SECONDS     = DateToFormat.getSeconds();

    var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    var strMONTH;
    var strDAY;
    var strHOUR;
    var strMINUTES;
    var strSECONDS;
    var Separator;

    if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
        strMONTH = "0" + MONTH;
    else
        strMONTH=MONTH;
    if(parseInt(DAY)< 10 && DAY.toString().length < 2)
        strDAY = "0" + DAY;
    else
        strDAY=DAY;
    if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
        strHOUR = "0" + HOUR;
    else
        strHOUR=HOUR;
    if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
        strMINUTES = "0" + MINUTES;
    else
        strMINUTES=MINUTES;
    if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
        strSECONDS = "0" + SECONDS;
    else
        strSECONDS=SECONDS;

    switch (formatString){
        case "hh:mm:ss":
            return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
        break;
        //More cases to meet your requirements.
    }
}
var time1 = date1.getTime();
var time2 = date2.getTime();
var totalMilisec = time2 - time1;

alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))

 /* ----------------------------------------------------------
 *  Field        | Full Form          | Short Form
 *  -------------|--------------------|-----------------------
 *  Year         | yyyy (4 digits)    | yy (2 digits)
 *  Month        | MMM (abbr.)        | MM (2 digits)
                 | NNN (name)         |
 *  Day of Month | dd (2 digits)      | 
 *  Day of Week  | EE (name)          | E (abbr)
 *  Hour (1-12)  | hh (2 digits)      | 
 *  Minute       | mm (2 digits)      | 
 *  Second       | ss (2 digits)      | 
 *  ----------------------------------------------------------
 */
function DateFormat(formatString,date){
    if (typeof date=='undefined'){
    var DateToFormat=new Date();
    }
    else{
        var DateToFormat=date;
    }
    var DAY         = DateToFormat.getDate();
    var DAYidx      = DateToFormat.getDay();
    var MONTH       = DateToFormat.getMonth()+1;
    var MONTHidx    = DateToFormat.getMonth();
    var YEAR        = DateToFormat.getYear();
    var FULL_YEAR   = DateToFormat.getFullYear();
    var HOUR        = DateToFormat.getHours();
    var MINUTES     = DateToFormat.getMinutes();
    var SECONDS     = DateToFormat.getSeconds();

    var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    var strMONTH;
    var strDAY;
    var strHOUR;
    var strMINUTES;
    var strSECONDS;
    var Separator;

    if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
        strMONTH = "0" + MONTH;
    else
        strMONTH=MONTH;
    if(parseInt(DAY)< 10 && DAY.toString().length < 2)
        strDAY = "0" + DAY;
    else
        strDAY=DAY;
    if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
        strHOUR = "0" + HOUR;
    else
        strHOUR=HOUR;
    if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
        strMINUTES = "0" + MINUTES;
    else
        strMINUTES=MINUTES;
    if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
        strSECONDS = "0" + SECONDS;
    else
        strSECONDS=SECONDS;

    switch (formatString){
        case "hh:mm:ss":
            return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
        break;
        //More cases to meet your requirements.
    }
}
顾北清歌寒 2025-01-10 10:14:44

我只是想对上面的好答案做一点解释:

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

在第二行,由于 1 小时有 3600 秒,因此我们将总秒数除以 3600 以获得总小时数。我们使用 parseInt 去除任何小数。如果 TotalSec 为 12600(3 个半小时),则 parseInt(totalSec / 3600) 将返回 3,因为我们将有 3 个完整小时。在这种情况下为什么我们需要%24?如果我们超过 24 小时,假设我们有 25 小时(90000 秒),那么这里的模将再次带我们回到 1,而不是返回 25。它将结果限制在 24 小时限制内,因为有 24 小时有一天。

当你看到这样的东西时:

25 % 24

这样想:

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

I just wanted to give a little explanation to the nice answer above:

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.

When you see something like this:

25 % 24

Think of it like this:

25 mod 24 or what is the remainder when we divide 25 by 24
初吻给了烟 2025-01-10 10:14:44

下面是给定的代码,它将秒转换为 hh-mm-ss 格式:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

在 JavaScript 中将秒转换为 HH-MM-SS 格式

below is the given code which will convert seconds into hh-mm-ss format:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

Get alternative method from Convert seconds to HH-MM-SS format in JavaScript

陌上芳菲 2025-01-10 10:14:44

这里的答案都不能满足我的要求,因为我希望能够处理

  1. 大量的秒(天)和
  2. 负数

虽然OP不需要这些,但覆盖边缘情况是很好的做法,特别是当它需要很少的努力时。

很明显,当OP说时,他的意思是“秒”。为什么要将你的函数固定在String上?

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

None of the answers here satisfies my requirements as I want to be able to handle

  1. Large numbers of seconds (days), and
  2. Negative numbers

Although those are not required by the OP, it's good practice to cover edge cases, especially when it takes little effort.

It's pretty obvious is that the OP means a NUMBER of seconds when he says seconds. Why would peg your function on String?

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
不忘初心 2025-01-10 10:14:44

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

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

function toScaledArray(n,scales){
  function* g(x, n=0){
    if(x>0) {
      yield x%(scales[n]||Infinity);
      yield* g(Math.floor(x/scales[n]),n+1)
    }
  }
  return [...g(n)]
}

console.log(toScaledArray(6,[10,10]))
console.log(toScaledArray(2000,[30,12]))
console.log(toScaledArray(45000,[24,30,12]))

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

> 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(){
  return [...(function* g(x,n=0,scales=[60,60]){if(x>0||n<2) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(this)].map((x,n)=>n<2?String(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秒”

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

You can use ES6 generator to create highly customizable time strings.

Here is the general function to convert a number to an array from a given scale:

function toScaledArray(n,scales){
  function* g(x, n=0){
    if(x>0) {
      yield x%(scales[n]||Infinity);
      yield* g(Math.floor(x/scales[n]),n+1)
    }
  }
  return [...g(n)]
}

console.log(toScaledArray(6,[10,10]))
console.log(toScaledArray(2000,[30,12]))
console.log(toScaledArray(45000,[24,30,12]))

So, we can use it to create time strings as follows:

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

The function can be also written in one line:

[...(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("-")

Functions above will omit the leading zeros, if you want to convert a string into precisely 'HH-MM-SS', you can use

[...(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("-")

Also, if what you need is '[H:]MM:SS', here we have:

Number.prototype.toTimeString = function(){
  return [...(function* g(x,n=0,scales=[60,60]){if(x>0||n<2) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(this)].map((x,n)=>n<2?String(x).padStart(2,'0'):x).reverse().join(":")
}

console.log(12,(12).toTimeString())
console.log(345,(345).toTimeString())
console.log(6789,(6789).toTimeString())

and you can also have D(ay) or even M(onth) and Y(ear) (not precisely though) as follows:

> 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'

Here the output means "3 years 11 months 18 days 21 hours 33 minutes and 9 seconds"

In conclusion, this is a highly customizable way to convert a number into scaled arrays, which can be used in time string conversion, human readable byte conversion or even change for paper money.

泼猴你往哪里跑 2025-01-10 10:14:44
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(':');
};
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(':');
};
深陷 2025-01-10 10:14:44

这是一个根据 powtac 的答案将秒转换为 hh-mm-ss 格式的函数 此处

jsfiddle

/** 
 * Convert seconds to hh-mm-ss format.
 * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
  var hours   = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // round seconds
  seconds = Math.round(seconds * 100) / 100

  var result = (hours < 10 ? "0" + hours : hours);
      result += "-" + (minutes < 10 ? "0" + minutes : minutes);
      result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

使用示例

var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10

Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here

jsfiddle

/** 
 * Convert seconds to hh-mm-ss format.
 * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
  var hours   = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // round seconds
  seconds = Math.round(seconds * 100) / 100

  var result = (hours < 10 ? "0" + hours : hours);
      result += "-" + (minutes < 10 ? "0" + minutes : minutes);
      result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

Example use

var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10
Spring初心 2025-01-10 10:14:44

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

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

如果你不想格式化零少于 10 个数字,你可以使用

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

}

示例代码 < a href="http://fiddly.org/1c476/1" rel="nofollow noreferrer">http://fiddly.org/1c476/1

There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here

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

if you don't wants formatted zero with less then 10 number, you can use

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

}

Sample Code http://fiddly.org/1c476/1

泪痕残 2025-01-10 10:14:44

在一行中,使用 TJ Crowder 的解决方案:

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

In one line, using T.J. Crowder's solution :

secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`

In one line, another solution that also count days :

secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`

Source : https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

冰葑 2025-01-10 10:14:44
var sec_to_hms = function(sec){
var min, hours;
     sec = sec - (min = Math.floor(sec/60))*60;
     min = min - (hours = Math.floor(min/60))*60;
     return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
}
alert(sec_to_hms(2442542));
var sec_to_hms = function(sec){
var min, hours;
     sec = sec - (min = Math.floor(sec/60))*60;
     min = min - (hours = Math.floor(min/60))*60;
     return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
}
alert(sec_to_hms(2442542));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文