Created
August 24, 2019 03:59
-
-
Save tevko/caf7ad5ae624800cc9c1d9895cfe35c4 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 (seconds) { | |
if (seconds === 0) { | |
return 'now'; | |
} | |
const dif = seconds * 1000; | |
const difSeconds = Math.floor(dif / 1000) % 60; | |
const difMinutes = Math.floor(dif / 60000) % 60; | |
const difHours = Math.floor(dif / 3.6e+6) % 24; | |
const difDays = Math.floor(dif / 8.64e+7) % 365; | |
const difYears = Math.floor(dif / 3.154e+10); | |
const format = (val, str) => { | |
if (Number(val) === 0) return; | |
if (Number(val) === 1) return `1 ${str}`; | |
return `${val} ${str}s` | |
} | |
const arr = [format(difYears, 'year'), format(difDays, 'day'), format(difHours, 'hour'), format(difMinutes, 'minute'), format(difSeconds, 'second')].filter(Boolean); | |
if (arr.length === 1) { | |
return arr.join(); | |
} else if (arr.length === 2) { | |
return arr.join(' and '); | |
} | |
return arr.map((c, i) => i === arr.length - 1 ? `and ${c}` : c).join(', ').replace(/\, and/, ' and'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment