开发时,后台经常返回秒数,但页面需要将秒数转换成天、时、分、秒展示,所以以下简单封装一下
秒数转换为 天、时、分、秒
const dayTime = (seconds) => {
let second = parseInt(seconds) % 60; // 直接取模数
let min = parseInt(seconds / 60) % 60;
let hour = parseInt(seconds / 60 / 60) % 24;
let day = parseInt(seconds / 60 / 60 / 24);
let result = second + "秒"; // 如果是 0 秒 ,直接赋值
if (seconds) {
second = (second >= 0 && second < 10) ? '0' + second : second
result = second + "秒";
}
if (seconds) {
min = (min >= 0 && min < 10) ? '0' + min : min
result = min + "分" + second + "秒";
}
if (hour) {
hour = (hour >= 0 && hour < 10) ? '0' + hour : hour
result = hour + "小时" + min + "分" + second + "秒";
}
if (day) {
day = (day >= 0 && day < 10) ? '0' + day : day
result = day + "天" + hour + "小时" + min + "分" + second + "秒";
}
return result;
}
let day = dayTime(320000)
console.log(day) // 03天16小时53分20秒
该函数适合于将大量秒数转换为易读的时长格式,适用于计时器、时长展示等需求。