使用 JavaScript 将秒转换为 HH-MM-SS?
如何使用 JavaScript 将秒转换为 HH-MM-SS
字符串?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使用 JavaScript 将秒转换为 HH-MM-SS
字符串?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(30)
您是否尝试过向 Date 对象添加秒?
样本:
https://jsfiddle.net/j5g2p0dc/5/
更新:
示例链接丢失,因此我创建了一个新链接。
Have you tried adding seconds to a Date object?
A sample:
https://jsfiddle.net/j5g2p0dc/5/
Updated:
Sample link was missing so I created a new one.
您还可以使用下面的代码:
You can also use below code:
对于任何使用 AngularJS 的人来说,一个简单的解决方案是使用 过滤值date API,根据请求的格式将毫秒转换为字符串。示例:
请注意,这需要毫秒,因此如果您要从秒转换(如原始问题的表述),您可能需要将 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:
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).
您可以借助 JavaScript Date 方法在没有任何外部 JavaScript 库的情况下做到这一点,如下所示:
或者按照 @Frank 的评论;一个衬垫:
You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:
Or, as per @Frank's comment; a one liner:
更新(2020):
请使用@Frank的一行解决方案:
如果SECONDS<3600并且您只想显示MM:SS,则使用下面的代码:
这是迄今为止最好的解决方案。
旧答案:
使用
Moment.js
库。Updated (2020):
Please use @Frank's one line solution:
If SECONDS<3600 and if you want to show only MM:SS then use below code:
It is by far the best solution.
Old answer:
Use the
Moment.js
library.我认为标准 Date 对象的任何内置功能都不会以比您自己进行数学计算更方便的方式为您完成此操作。
例子:
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.
Example:
我知道这有点旧,但是......
ES2015:
它将输出:
I know this is kinda old, but...
ES2015:
It will output:
正如 Cleiton 在他的回答中指出的,moment.js 可用于此目的:
As Cleiton pointed out in his answer, moment.js can be used for this:
这是一个转换时间的简单函数,可能会有所帮助
Here's a simple function for converting times that might help
这可以解决问题:(
源自此处)
This does the trick:
(Sourced from here)
我们可以让这个函数变得更短更清晰,但这会降低可读性,所以我们会尽可能简单和稳定地编写它。
或者您可以在此处检查此工作:
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:
我认为最通用(且神秘)的解决方案可能是这个
或者复制并复制粘贴最短的版本
一些示例输出:
工作原理
算法
将各个金额保存在数组中以便于格式化也很好。
例如,输入 3785 秒,输出应为
[1, 3, 5]
,即 1 小时 3 分 5 秒。创建管道
将 3600 和 60 常量命名为“断点”,您可以将此算法写入函数,因为
它返回一个数组,其中第一项是给定断点的数量,数组的其余部分由回调给出。
在回调函数中重用
divideAndAppend
将为您提供一个组合管道divideAndAppend
函数。其中每一项计算每个给定断点的数量并将其附加到数组中以生成所需的输出。
然后,您还需要结束该管道的“最终”回调。换句话说,您使用了所有断点,现在只剩下剩余的断点。
由于您已经在 3) 处得到了答案,因此您应该使用某种恒等函数,在本例中
remainder => [余数]
。您现在可以像这样编写管道了,
很酷吗?
使用 for 循环进行泛化
现在,您可以使用可变数量的断点进行泛化,并创建一个 for 循环,将各个
divideAndAppend
函数组合成管道。
您从恒等函数 r1 => 开始[r1],然后使用
60
断点,最后使用3600
断点。使用 Array.prototype.reduce()
现在您可以将这个 for 循环重写为 reducer,以获得更短、更实用的代码。换句话说,将函数组合重写到reducer 中。
累加器 ppln 是管道,您正在使用它的早期版本来编写它。初始管道是 r =>; [r]。
您现在可以内联函数
divideAndAppend
并使用Array.prototype.reduceRight
,它与[].reverse().reduce(...)< /code> 来设置断点
定义更加自然。
这是最终的形式。然后,您只需应用映射到左侧填充 0 的字符串,并使用
:
分隔符连接字符串;更多泛化
将减速器包装到函数中,
您现在可以使用非常通用的算法。例如:
轻松转换(奇怪的)美国长度标准
给定标准
123456 英寸 = 1 英里、1669 码、1 英尺和 0 英寸
或者您可以转换为十进制或二进制表示
也适用于浮点断点
由于Javascript支持带有浮点数的
mod
运算符,因此您还可以执行no的边缘情况断点也自然被覆盖
I think the most general (and cryptic) solution could be this
Or to copy & paste the shortest version
Some example outputs:
How it works
Algorithm
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
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 composeddivideAndAppend
functions. Each one of thesecomputes 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
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 intothe pipeline.
You start with the identity function
r1 => [r1]
, then use the60
breakpoint and finally use the3600
breakpoint.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.
The accumulator
ppln
is the pipeline and you are composing it using the previous version of it. The initial pipeline isr => [r]
.You can now inline the function
divideAndAppend
and useArray.prototype.reduceRight
which is the same as[].reverse().reduce(...)
to make the breakpointsdefinitions more natural.
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
you now have very general algorithm you can work with. For example:
Convert easily (the weird) us length standards
Given the standards
123456 in = 1 mi, 1669 yd, 1 feet and 0 in
Or you can somewhat convert to decimal or binary representations
Works also with floating point breakpoints
Since Javascript supports
mod
operator with floating point numbers, you can also doThe edge case of no breakpoints is also naturally covered
试试这个:
Try this:
这是 Number 类的扩展。 toHHMMSS() 将秒转换为 hh:mm:ss 字符串。
Here is an extension to Number class. toHHMMSS() converts seconds to an hh:mm:ss string.
适合新手的易于理解的版本:
Easy to follow version for noobies:
这个函数应该做到这一点:
在不传递分隔符的情况下,它使用
:
作为(默认)分隔符:如果您想使用
-
作为分隔符,只需将其作为第二个参数:另请参阅这个Fiddle。
This function should do it :
Without passing a separator, it uses
:
as the (default) separator :If you want to use
-
as a separator, just pass it as the second parameter:See also this Fiddle.
插话这个旧线程 - OP 表示 HH:MM:SS,并且许多解决方案都有效,直到您意识到您需要列出的时间超过 24 小时。也许您只需要一行代码。在这里:
它返回 H+:MM:SS。要使用它,只需使用:
...我试图让它使用尽可能少的代码,以获得一种很好的单行方法。
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:
It returns H+:MM:SS. To use it, simply use:
...I tried to get it to use the least amount of code possible, for a nice one-liner approach.
在查看了所有答案并对其中大多数答案不满意之后,这就是我想到的。我知道我已经很晚才开始谈话,但无论如何,事情就在这里。
我创建一个新的 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.
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
对于HH:MM:SS.MS(eq:“00:04:33.637”)的特殊情况。 html#time-duration-syntax" rel="nofollow noreferrer">FFMPEG 指定毫秒。
使用示例,毫秒传输计时器:
绑定到媒体元素的示例用法
在问题之外,那些用 php 编写的函数:
For the special case of HH:MM:SS.MS (eq: "00:04:33.637") as used by FFMPEG to specify milliseconds.
Example usage, a milliseconds transport timer:
Example usage, binded to a media element
Outside the question, those functions written in php:
将秒转换为 hh:mm:ss 格式的简单函数:
Simple function to convert seconds into in hh:mm:ss format :
我只是想对上面的好答案做一点解释:
在第二行,由于 1 小时有 3600 秒,因此我们将总秒数除以 3600 以获得总小时数。我们使用 parseInt 去除任何小数。如果 TotalSec 为 12600(3 个半小时),则 parseInt(totalSec / 3600) 将返回 3,因为我们将有 3 个完整小时。在这种情况下为什么我们需要%24?如果我们超过 24 小时,假设我们有 25 小时(90000 秒),那么这里的模将再次带我们回到 1,而不是返回 25。它将结果限制在 24 小时限制内,因为有 24 小时有一天。
当你看到这样的东西时:
这样想:
I just wanted to give a little explanation to the nice answer above:
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:
Think of it like this:
下面是给定的代码,它将秒转换为 hh-mm-ss 格式:
从 在 JavaScript 中将秒转换为 HH-MM-SS 格式
below is the given code which will convert seconds into hh-mm-ss format:
Get alternative method from Convert seconds to HH-MM-SS format in JavaScript
这里的答案都不能满足我的要求,因为我希望能够处理
虽然OP不需要这些,但覆盖边缘情况是很好的做法,特别是当它需要很少的努力时。
很明显,当OP说秒时,他的意思是“秒”。为什么要将你的函数固定在
String
上?None of the answers here satisfies my requirements as I want to be able to handle
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
?您可以使用 ES6 生成器 来创建高度可定制的时间字符串。
以下是将数字从给定比例转换为数组的通用函数:
因此,我们可以使用它来创建时间字符串,如下所示:
该函数也可以写在一行中:
上面的函数会省略前导零,如果你想将字符串转换为精确的“HH-MM-SS”,你可以另外
,如果您需要的是“[H:]MM:SS”,这里我们有:
您还可以使用
D(ay)
甚至M(onth)
和Y(ear)
(但不完全是),如下所示:输出的意思是“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:
So, we can use it to create time strings as follows:
The function can be also written in one line:
Functions above will omit the leading zeros, if you want to convert a string into precisely 'HH-MM-SS', you can use
Also, if what you need is '[H:]MM:SS', here we have:
and you can also have
D(ay)
or evenM(onth)
andY(ear)
(not precisely though) as follows: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.
这是一个根据 powtac 的答案将秒转换为 hh-mm-ss 格式的函数 此处
jsfiddle
使用示例
Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here
jsfiddle
Example use
有很多选项可以解决这个问题,显然有很好的选项建议,但我想在这里添加一个更优化的代码,
如果你不想格式化零少于 10 个数字,你可以使用
}
示例代码 < 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
if you don't wants formatted zero with less then 10 number, you can use
}
Sample Code http://fiddly.org/1c476/1
在一行中,使用 TJ Crowder 的解决方案:
在一行中,另一种也计算天数的解决方案:
来源:https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276
In one line, using T.J. Crowder's solution :
In one line, another solution that also count days :
Source : https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276