Skip to content

Instantly share code, notes, and snippets.

@ChJJin
Created August 14, 2017 02:34
Show Gist options
  • Save ChJJin/10384536612db63482b3dcfe2b0fd815 to your computer and use it in GitHub Desktop.
Save ChJJin/10384536612db63482b3dcfe2b0fd815 to your computer and use it in GitHub Desktop.
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