Created
August 14, 2017 02:34
-
-
Save ChJJin/10384536612db63482b3dcfe2b0fd815 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatDuration(dur) { | |
const timeRange = [60, 60, 24, 1000]; | |
const units = ['秒', '分钟', '小时', '天']; | |
let i = 0; | |
let total = dur; | |
function getUnitStr(pad) { | |
const larger = (total / timeRange[i]) >= 1; | |
const base = total % timeRange[i]; | |
if (base === 0) return ''; | |
const num = pad && larger ? `0${base}`.slice(-2) : base; | |
return `${num} ${units[i]}`; | |
} | |
// 秒需要补0 | |
let str = getUnitStr(true); | |
while (total >= timeRange[i]) { | |
total = Math.floor(total / timeRange[i]); | |
i++; | |
str = `${getUnitStr()} ${str}`; | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment