Skip to content

Instantly share code, notes, and snippets.

@srph
Created May 17, 2019 22:37
Show Gist options
  • Save srph/24cb35261d1ef822da891f85fd16595d to your computer and use it in GitHub Desktop.
Save srph/24cb35261d1ef822da891f85fd16595d to your computer and use it in GitHub Desktop.
JS: Convert seconds to readable time
/**
* Converts seconds to readable time (e.g., 03:45:24, 45:34, 34)
*/
export default function toReadableTime(seconds: number): string {
const hh = Math.floor(seconds / 3600)
const mm = Math.floor((seconds % 3600 / 60))
const ss = Math.floor(seconds % 60)
if (hh >= 1) {
return [hh, mm, ss].map(t => String(t).padStart(2, '0')).join(':')
}
if (mm >= 1) {
return [mm, ss].map(t => String(t).padStart(2, '0')).join(':')
}
return `${ss}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment