JavaScript:日期格式化——js毫秒数转换成时间
返回给定毫秒数的可读格式
思路
- 将ms除以适当的值,以获得day、hour和minute的值;
- 将Object.entries() 与Array.prototype.filter()配合使用以仅保留非零值;
- 使用Array.prototype.map()为每个值创建字符串,并适当地进行复数化;
- 使用String.prototype.join(' ')将值组合成字符串。
实现代码
const formatDuration = ( ms ) => {
if(ms < 0) ms = -ms;
let time = {
day: Math.floor(ms / 86400000),
hour: Math.floor(ms / 3600000) % 24,
minute: Math.floor(ms / 60000) % 60
}
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(([key, val])=>{
if(key === 'day') return `${val}天`
if(key === 'hour') return `${val}时`
if(key === 'minute') return `${val}分`
})
.join(' ');
}
测试代码
let t1 = formatDuration(62341001);
console.log(t1);
let t2 = formatDuration(34325055574);
console.log(t2);
测试结果
17时 19分
397天 6时 44分
相关推荐
-
Linux C Socket Api详解2024-05-19 20:55:28
-
在Ubuntu Linux上使用开源的Swift2024-05-19 19:54:16
-
Linux中fcntl()、lockf、flock的区别2024-05-19 18:51:55
-
Linux错误代码:errno.h与返回值 -EINVAL2024-05-19 17:57:27
-
Linux运维工程师必知:如何根据内存使用情况对 top 命令进行排序?
Linux运维工程师必知:如何根据内存使用情况对 top 命令进行排序?2024-05-19 16:52:51