JavaScript 秒到时间字符串,格式为 hh:mm:ss
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6312993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript seconds to time string with format hh:mm:ss
提问by medk
I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)
我想将持续时间(即秒数)转换为以冒号分隔的时间字符串 (hh:mm:ss)
I found some useful answers here but they all talk about converting to x hours and x minutes format.
我在这里找到了一些有用的答案,但他们都在谈论转换为 x 小时和 x 分钟的格式。
So is there a tiny snippet that does this in jQuery or just raw JavaScript?
那么是否有一个小片段可以在 jQuery 或原始 JavaScript 中执行此操作?
回答by powtac
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
You can use it now like:
您现在可以像这样使用它:
alert("5678".toHHMMSS());
Working snippet:
工作片段:
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours + ':' + minutes + ':' + seconds;
}
console.log("5678".toHHMMSS());
回答by Harish Anchu
You can manage to do this without any external JS library with the help of JS Date method like following:
借助 JS Date 方法,您可以在没有任何外部 JS 库的情况下设法做到这一点,如下所示:
var date = new Date(0);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substr(11, 8);
console.log(timeString)
回答by Raj
To get the time part in the format hh:MM:ss
, you can use this regular expression:
要获取格式中的时间部分hh:MM:ss
,您可以使用以下正则表达式:
(This was mentioned above in same post by someone, thanks for that.)
(这在上面有人在同一篇文章中提到过,谢谢。)
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "");
console.log(myDate)
回答by JellicleCat
I recommend ordinary javascript, using the Date object:
我推荐普通的 javascript,使用 Date 对象:
var seconds = 9999;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);
(Of course, the Date object created will have an actual date associated with it, but that data is extraneous, so for these purposes, you don't have to worry about it.)
(当然,创建的 Date 对象会有一个与之关联的实际日期,但该数据是无关紧要的,因此出于这些目的,您不必担心。)
回答by Ash Burlaczenko
A Google search turned up this result:
谷歌搜索结果如下:
function secondsToTime(secs)
{
secs = Math.round(secs);
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
回答by jottos
Variation on a theme. Handles single digit seconds a little differently
一个主题的变化。处理个位数秒的方式略有不同
seconds2time(0) -> "0s"
seconds2time(59) -> "59s"
seconds2time(60) -> "1:00"
seconds2time(1000) -> "16:40"
seconds2time(4000) -> "1:06:40"
function seconds2time (seconds) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
var seconds = seconds - (hours * 3600) - (minutes * 60);
var time = "";
if (hours != 0) {
time = hours+":";
}
if (minutes != 0 || time !== "") {
minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
time += minutes+":";
}
if (time === "") {
time = seconds+"s";
}
else {
time += (seconds < 10) ? "0"+seconds : String(seconds);
}
return time;
}
回答by Tom Esterez
Here's my take on it:
这是我的看法:
function formatTime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.round(seconds % 60);
return [
h,
m > 9 ? m : (h ? '0' + m : m || '0'),
s > 9 ? s : '0' + s
].filter(Boolean).join(':');
}
Expected results:
预期成绩:
const expect = require('expect');
expect(formatTime(0)).toEqual('0:00');
expect(formatTime(1)).toEqual('0:01');
expect(formatTime(599)).toEqual('9:59');
expect(formatTime(600)).toEqual('10:00');
expect(formatTime(3600)).toEqual('1:00:00');
expect(formatTime(360009)).toEqual('100:00:09');
expect(formatTime(0.2)).toEqual('0:00');
回答by Serge K.
I like the first answer. There some optimisations:
我喜欢第一个答案。有一些优化:
source data is a Number. additional calculations is not needed.
much excess computing
源数据是一个数字。不需要额外的计算。
过多的计算
Result code:
结果代码:
Number.prototype.toHHMMSS = function () {
var seconds = Math.floor(this),
hours = Math.floor(seconds / 3600);
seconds -= hours*3600;
var minutes = Math.floor(seconds / 60);
seconds -= minutes*60;
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
回答by Pradeep
Using the amazing moment.jslibrary:
使用令人惊叹的moment.js库:
function humanizeDuration(input, units ) {
// units is a string with possible values of y, M, w, d, h, m, s, ms
var duration = moment().startOf('day').add(units, input),
format = "";
if(duration.hour() > 0){ format += "H [hours] "; }
if(duration.minute() > 0){ format += "m [minutes] "; }
format += " s [seconds]";
return duration.format(format);
}
This allows you to specify any duration be it hours, minutes, seconds, mills, and returns a human readable version.
这允许您指定任何持续时间,无论是小时、分钟、秒、米尔斯,并返回一个人类可读的版本。
回答by meiyang
function formatTime(seconds) {
return [
parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0")
}