秒数转成中文 天时分秒格式

/**
 * 秒数转成中文时分秒格式
 * @param  {string|number} val - 秒数
 * @param  {boolean} complementNum=false - 个位是否需要补齐为十位: 1-> 01
 * @param  {boolean} complementStr=false - 为0时是否需要补齐天时分秒: 1秒 -> 0小时0分钟1秒
 */
const getStrTime = (val, complementNum = false, complementStr = false) => { const num = Number(val) if (isNaN(num)) return '' if (num <= 0) { return 0 } const day = parseInt(num / (60 * 60 * 24)) const hour = parseInt(num % (60 * 60 * 24) / (60 * 60)) const min = parseInt(num % (60 * 60 * 24) % (60 * 60) / 60) const second = parseInt(num % 60) let list = [day, hour, min, second] if (complementNum) { list.forEach((item, index) => { if (index > 0) { // day不需要这个机制 list[index] = item > 9 ? item : '0' + item } }) } const unitList = ['天', '小时', '分钟', '秒'] const res = list.reduce((result, target, index) => { let str = target + unitList[index] if (!complementStr) str = Number(target) > 0 ? str : '' return result + str }, '') return res }

getStrTime(100) //'1分钟40秒'
getStrTime(100,true) //'01分钟40秒'
getStrTime(100,true,true) //''0天00小时01分钟40秒''
getStrTime(100,false,true) //'0天0小时1分钟40秒'
 

 

posted @ 2023-08-17 16:14  william_new  阅读(29)  评论(0编辑  收藏  举报