如何使用JavaScript将秒转换为HH-MM-SS字符串?
当前回答
我只是想对上面这个不错的答案做一点解释:
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
其他回答
这里有一个转换时间的简单函数,可能会有帮助
function formatSeconds(seconds) {
var date = new Date(1970,0,1);
date.setSeconds(seconds);
return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
当我想象一个时钟或计时器时,我会这样做:
const secondsTo_HHMMSS = (seconds) => {
//format to a readable friendly timer
let hour = Math.floor(seconds / 3600);
let minute = Math.floor((seconds % 3600) / 60);
let second = seconds % 60;
if(hour.toString().length === 1) {
hour = `0${hour}`;
}
if(minute.toString().length === 1) {
minute = `0${minute}`;
}
if(second.toString().length === 1) {
second = `0${second}`;
};
let timer = `${hour}-${minute}-${second}`;
return timer;
}
一个好的选择是使用Intl.DateTimeFormat。例子:
const timeFormat = new Intl.DateTimeFormat('es-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: 'UTC'
});
const endTimeFormatted = timeFormat.format(new Date(SECS * 1000); //hour in secs
有很多解决这个问题的选项,显然有很好的选项建议,但我想在这里添加一个更优化的代码
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(":");
}
如果你不想格式化0和小于10的数字,你可以使用
function formatSeconds(sec) {
return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);
}
示例代码http://fiddly.org/1c476/1
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));
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie