Vue中的时间转换,把毫秒换算成正常时间

本文详细介绍了如何将不同单位的毫秒数转换为易读的时间格式,包括秒、分钟、小时和天数。通过使用JavaScript的Math.floor和Math.round函数进行计算,并通过条件判断和三元运算符处理个位数前的零,实现完整的时间格式展示。同时,展示了在前端展示中如何优化布局,确保不同时间单位在一行内正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、53200毫秒

只到秒,没有分,没有进位,只要简单的除以1000就可以了

{{Math.round(time0/1000)}}

二、3022222毫秒

进位到分钟,需要除以60,然后把小数点前后部分的数值分开来处理

				{{Math.floor(Math.round(time/1000)/60)}}:
				{{Math.round(time/1000)%60}}

三、32300432毫秒

进位到了小时,需要把除以60得到的整数部分,再除以60,把得到的数的小数和整数部分分开继续处理

			{{Math.floor(Math.floor(Math.round(time2/1000)/60)/24) }}:
			{{Math.floor(Math.round(time2/1000)/60)%24 }}:
			{{Math.round(time2/1000)%60}}

四、4242323234毫秒

分步除以60、60、24,一共要处理四个数

			{{Math.floor(Math.floor(Math.floor(Math.round(time3/1000)/60)/60)/24)}}天
			{{Math.floor(Math.floor(Math.round(time3/1000)/60)/60)%24}}时
			{{Math.floor(Math.round(time3/1000)/60)%60}}分
			{{Math.round(time3/1000)%60}}秒

显示结果:

五、53200毫秒

把第一步的数和第四步的代码结合起来看看,出来的是什么结果

这样显示明显不合适,0的时候就可以不用显示

加个v-show来做下判断,代码就改进成下面这样

给div都加上display: inline-block;改成行内块,让它们能显示在同一行

            <div>
				<div v-show="time0/1000>86400" style="display: inline-block;">
					{{Math.floor(Math.floor(Math.floor(Math.round(time0/1000)/60)/60)/24)}}天
				</div>
				<div v-show="time0/1000>3600" style="display: inline-block;">
					{{Math.floor(Math.floor(Math.round(time0/1000)/60)/60)%24}}时
				</div>			
				<div v-show="time0/1000>60" style="display: inline-block;">
					{{Math.floor(Math.round(time0/1000)/60)%60}}分
				</div>			
					{{Math.round(time0/1000)%60}}秒
			</div>

显示就正常了

再加个三目运算把个位数的前面都拼接上0

然后代码一下就变得无比的长

			<div>
				<div v-show="time0/1000>86400" style="display: inline-block;">
					{{Math.floor(Math.floor(Math.floor(Math.round(time0/1000)/60)/60)/24)<10?('0'+Math.floor(Math.floor(Math.floor(Math.round(time0/1000)/60)/60)/24)):Math.floor(Math.floor(Math.floor(Math.round(time0/1000)/60)/60)/24)}}天
				</div>
				<div v-show="time0/1000>3600" style="display: inline-block;">
					{{Math.floor(Math.floor(Math.round(time0/1000)/60)/60)%24<10?('0'+Math.floor(Math.floor(Math.round(time0/1000)/60)/60)%24):Math.floor(Math.floor(Math.round(time0/1000)/60)/60)%24}}时
				</div>			
				<div v-show="time0/1000>60" style="display: inline-block;">
					{{Math.floor(Math.round(time0/1000)/60)%60<10?('0'+Math.floor(Math.round(time0/1000)/60)%60):Math.floor(Math.round(time0/1000)/60)%60}}分
				</div>			
					{{Math.round(time0/1000)%60<10?('0'+Math.round(time0/1000)%60):Math.round(time0/1000)%60}}秒
			</div>

显示效果对比

重点:

%:取余

Math.floor():相当于省去小数后的数字

Math.round():四舍五入 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

youngcave2

等待第一笔打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值