Skip to content

Instantly share code, notes, and snippets.

@Dewep
Created October 26, 2016 14:05
Show Gist options
  • Save Dewep/7358210b2d7aa9a2f924865bb7b5c6b9 to your computer and use it in GitHub Desktop.
Save Dewep/7358210b2d7aa9a2f924865bb7b5c6b9 to your computer and use it in GitHub Desktop.
Duration to string
/* Units: ms, s, m, h, d */
window.durationToString = function (duration, unit, minRate) {
var str = ''
unit = unit.toLowerCase()
if (minRate === undefined) {
minRate = 0.02
}
if (unit.startsWith('s')) {
duration *= 1000
} else if (unit == 'm' || unit.startsWith('min')) {
duration *= 1000 * 60
} else if (unit.startsWith('h')) {
duration *= 1000 * 60 * 60
} else if (unit.startsWith('d') || unit.startsWith('j')) {
duration *= 1000 * 60 * 60 * 24
}
var saveDuration = duration
var checkUnit = function (interval, name, twoDigitsMin) {
var val = ~~(duration / interval)
duration = duration - val * interval
if (val > 0 && (val * interval) / saveDuration >= minRate) {
if (val < 10 && twoDigitsMin === true) {
str += '0'
}
str += val + name
}
}
checkUnit(1000 * 60 * 60 * 24, 'j')
checkUnit(1000 * 60 * 60, 'h', true)
checkUnit(1000 * 60, 'm', true)
checkUnit(1000, 's', true)
checkUnit(1, 'ms')
return str
}
/* durationToString(61, 'm') 01h */
/* durationToString(62, 'm') 01h02m */
/* durationToString(61, 'm', 0) 01h01m */
/* durationToString(123.32, 'm') 02h03m */
/* durationToString(123.32, 'm', 0) 02h03m19s200ms */
/* durationToString(61, 'h') 2j13h */
/* durationToString(3, 'd') 3j */
/* durationToString(3.632, 'd') 3j15h */
/* durationToString(3.632, 'd', 0) 3j15h10m04s800ms */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment