(04)VUE/JS秒转天时分秒并补零

文章提供了四种JavaScript函数,分别用于将给定的秒数转换为小时、分钟和秒的格式。这些方法通过数学运算和条件判断来处理位数不足的情况,确保输出的时间格式正确,例如01:16:28。
摘要由CSDN通过智能技术生成

转换为时分秒的公式
方法一:(极简)

function getTime(time) {
	// 转换为式分秒
	let h = parseInt(time / 60 / 60 % 24)
	h = h < 10 ? '0' + h : h
	let m = parseInt(time / 60 % 60)
	m = m < 10 ? '0' + m : m
	let s = parseInt(time % 60)
	s = s < 10 ? '0' + s : s
	var res = [h, m, s]
	console.log(`${res[0]}时${res[1]}分${res[2]}秒`)
	console.log(`${res[0]}:${res[1]}:${res[2]}`)
}

getTime(4588) // 01时16分28秒  或  01:16:28

方法二:

function secTotime(s) {
	var t = '';
	if(s > -1){
		var hour = Math.floor(s/3600)
		var min = Math.floor(s/60) % 60
		var sec = s % 60
		if(hour < 10) {
		  t = '0'+ hour + ":"
		} else { 
		  t = hour + ":"
		} 
		if(min < 10){
		  t += "0"
		} 
		t += min + ":"
		if(sec < 10){
		  t += "0"
		} 
		t += sec.toFixed(0)
	} 
	console.log(t);
	return t
}

secTotime(4588) // 01:16:28

方法三:

function formatSeconds(value) {
	let result = parseInt(value);
	let y =
		Math.floor(result / 86400) < 10 ?
		"0" + Math.floor(result / 86400) :
		Math.floor(result / 86400);
	let h =
		Math.floor((result / 3600) % 24) < 10 ?
		"0" + Math.floor((result / 3600) % 24) :
		Math.floor((result / 3600) % 24);
	let m =
		Math.floor((result / 60) % 60) < 10 ?
		"0" + Math.floor((result / 60) % 60) :
		Math.floor((result / 60) % 60);
	let s =
		Math.floor(result % 60) < 10 ?
		"0" + Math.floor(result % 60) :
		Math.floor(result % 60);
	let res = "";
	if (y !== "00") res += `${y}天`;
	if (h !== "00") res += `${h}时`;
	if (m !== "00") res += `${m}分`;
	res += `${s}秒`;
	return res;
}

console.log(formatSeconds(456688)); // 05天06时51分28秒

方法四:

function formatSeconds(value) {
	let result = parseInt(value)
	let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600)
	let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60))
	let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60))
	result = `${h}:${m}:${s}`
	return result
}

console.log(formatSeconds(4588));  // 01:16:28
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值