如何使用JavaScript将秒转换为HH-MM-SS字符串?
当前回答
下面是将秒转换为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格式的替代方法
其他回答
正如Cleiton在他的回答中指出的,moment.js可以用于:
moment().startOf('day')
.seconds(15457)
.format('H:mm:ss');
更新(2020):
请使用@Frank的一句话解决方案:
new Date(SECONDS * 1000).toISOString().substring(11, 16)
如果SECONDS<3600并且你只想显示MM:SS,那么使用下面的代码:
new Date(SECONDS * 1000).toISOString().substring(14, 19)
这是目前为止最好的解决办法。
旧的回答:
使用Moment.js库。
这招很管用:
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;
}
(来源此处)
这里有一个转换时间的简单函数,可能会有帮助
function formatSeconds(seconds) {
var date = new Date(1970,0,1);
date.setSeconds(seconds);
return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
我只是想对上面这个不错的答案做一点解释:
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
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 前一个月的Python日期
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?