如何使用JavaScript将秒转换为HH-MM-SS字符串?
当前回答
我知道这有点老了,但是…
ES2015:
var toHHMMSS = (secs) => {
var sec_num = parseInt(secs, 10)
var hours = Math.floor(sec_num / 3600)
var minutes = Math.floor(sec_num / 60) % 60
var seconds = sec_num % 60
return [hours,minutes,seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v,i) => v !== "00" || i > 0)
.join(":")
}
它将输出:
toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18
其他回答
下面是一个函数,根据powtac的答案将秒转换为hh-mm-ss格式
斯菲德尔
/**
* Convert seconds to hh-mm-ss format.
* @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
var hours = Math.floor(totalSeconds / 3600);
var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
// round seconds
seconds = Math.round(seconds * 100) / 100
var result = (hours < 10 ? "0" + hours : hours);
result += "-" + (minutes < 10 ? "0" + minutes : minutes);
result += "-" + (seconds < 10 ? "0" + seconds : seconds);
return result;
}
示例使用
var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10
你也可以使用下面的代码:
int ss = nDur%60;
nDur = nDur/60;
int mm = nDur%60;
int hh = nDur/60;
export const secondsToHHMMSS = (seconds) => {
const HH = `${Math.floor(seconds / 3600)}`.padStart(2, '0');
const MM = `${Math.floor(seconds / 60) % 60}`.padStart(2, '0');
const SS = `${Math.floor(seconds % 60)}`.padStart(2, '0');
return [HH, MM, SS].join(':');
};
当我想象一个时钟或计时器时,我会这样做:
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;
}
这里有一个转换时间的简单函数,可能会有帮助
function formatSeconds(seconds) {
var date = new Date(1970,0,1);
date.setSeconds(seconds);
return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
推荐文章
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 相当于字符串。jQuery格式
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?