js 计算给定的毫秒值所占的时长信息。格式化时长工具代码片段
代码
function formatTime(millis, reserve=false){
let units = [
{
unitName: '毫秒',
threshold: 1000,
},
{
unitName: '秒',
threshold: 60,
},
{
unitName: '分钟',
threshold: 60,
},
{
unitName: '小时',
threshold: 24,
},
{
unitName: '天',
threshold: 30,
},
]
let tempTimes = [millis,0];
let timeParts = [];
for(let i=0, end=false;i<units.length ;i++) {
let unit = units[i];
let tempTime = tempTimes[0];
if(tempTime < unit.threshold){
timeParts.push({
matchUnit: units[i],
unitValue: tempTime
})
}else if(i >= units.length - 1){
timeParts.push({
matchUnit: units[i],
unitValue: tempTime
})
}else {
tempTimes[0] = Math.trunc(tempTime / unit.threshold);
tempTimes[1] = tempTime % unit.threshold;
timeParts.push({
matchUnit: units[i],
unitValue: tempTimes[1]
})
}
}
return reserve ? timeParts.reverse() : timeParts;
}
# 示例
formatTime(60*65)
复制请注明出处,在世界中挣扎的灰太狼