我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
当前回答
我不喜欢在JavaScript中为标准数据类型添加属性,所以我建议这样做:
/**
* Format a duration in seconds to a human readable format using the notion
* "h+:mm:ss", e.g. "4:40:78". Negative durations are preceeded by "-".
*
* @param t Duration in seconds
* @return The formatted duration string
*/
var readableDuration = (function() {
// Each unit is an object with a suffix s and divisor d
var units = [
{s: '', d: 1}, // Seconds
{s: ':', d: 60}, // Minutes
{s: ':', d: 60}, // Hours
];
// Closure function
return function(t) {
t = parseInt(t); // In order to use modulus
var trunc, n = Math.abs(t), i, out = []; // out: list of strings to concat
for (i = 0; i < units.length; i++) {
n = Math.floor(n / units[i].d); // Total number of this unit
// Truncate e.g. 26h to 2h using modulus with next unit divisor
if (i+1 < units.length) // Tweak substr with two digits
trunc = ('00'+ n % units[i+1].d).substr(-2, 2); // …if not final unit
else
trunc = n;
out.unshift(''+ trunc + units[i].s); // Output
}
(t < 0) ? out.unshift('-') : null; // Handle negative durations
return out.join('');
};
})();
用法:
var str = readableDuration(3808); // "1:03:28"
我还创建了一个更通用的版本。主要的区别是它接受毫秒(这是JS中的标准时间单位),而输出格式使用空格。
其他回答
我喜欢Powtac的答案,但我想在angular.js中使用它,所以我用他的代码创建了一个过滤器。
.filter('HHMMSS', ['$filter', function ($filter) {
return function (input, decimals) {
var sec_num = parseInt(input, 10),
decimal = parseFloat(input) - sec_num,
hours = Math.floor(sec_num / 3600),
minutes = Math.floor((sec_num - (hours * 3600)) / 60),
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;}
var time = hours+':'+minutes+':'+seconds;
if (decimals > 0) {
time += '.' + $filter('number')(decimal, decimals).substr(2);
}
return time;
};
}])
它在功能上是相同的,除了我添加了一个可选的小数字段来显示小数秒。像使用其他过滤器一样使用它:
{{elapsedTime | HHMMSS}}显示:01:23:45
{{elapsedTime | HHMMSS: 3}}显示:01:23:45.678
//secondsToTime();
var t = wachttijd_sec; // your seconds
var hour = Math.floor(t/3600);
if(hour < 10){
hour = '0'+hour;
}
var time = hour+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2);
//would output: 00:00:00 > +100:00:00
即使超过24小时也能保持倒计时
下面是一个使用Date.prototype.toLocaleTimeString()的例子。我选择GB作为语言,因为美国在最初的小时显示的是24而不是00。此外,我选择Etc/UTC作为时区,因为UTC在tz数据库时区列表中是它的别名。
const formatTime = (seconds) => 新日期(秒* 1000)。toLocaleTimeString(“en”{ 时区:“等/ UTC ', hour12:假的, 小时:“便是”, 分钟:“便是”, 第二:“便是” }); console.log (formatTime (75));/ / 00:01:15 .as-console-wrapper {top: 0;Max-height: 100%重要;}
下面是相同的示例,但是使用了Intl.DateTimeFormat。这个变体允许您实例化一个可重用的格式化器对象,这更具有性能。
const dateFormatter = new Intl。DateTimeFormat(“en”{ 时区:“等/ UTC ', hour12:假的, 小时:“便是”, 分钟:“便是”, 第二:“便是” }); const formatTime = (seconds) => dateFormatter。format(new Date(seconds * 1000)); console.log (formatTime (75));/ / 00:01:15 .as-console-wrapper {top: 0;Max-height: 100%重要;}
最普遍的答案是
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"
详见https://stackoverflow.com/a/66504936/1310733
我会给artem的答案投票,但我是一个新海报。我确实扩展了他的解决方案,虽然不是OP要求的如下
t=(new Date()).toString().split(" ");
timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]);
得到
0410月16:31:28太平洋时间
这对我很有用……
但如果你从一个时间量开始,我会用两个函数;一个用于格式化和填充,一个用于计算:
function sec2hms(timect){
if(timect=== undefined||timect==0||timect === null){return ''};
//timect is seconds, NOT milliseconds
var se=timect % 60; //the remainder after div by 60
timect = Math.floor(timect/60);
var mi=timect % 60; //the remainder after div by 60
timect = Math.floor(timect/60);
var hr = timect % 24; //the remainder after div by 24
var dy = Math.floor(timect/24);
return padify (se, mi, hr, dy);
}
function padify (se, mi, hr, dy){
hr = hr<10?"0"+hr:hr;
mi = mi<10?"0"+mi:mi;
se = se<10?"0"+se:se;
dy = dy>0?dy+"d ":"";
return dy+hr+":"+mi+":"+se;
}