Skip to content

Instantly share code, notes, and snippets.

@mra-dev
Last active June 26, 2022 16:15
Show Gist options
  • Save mra-dev/d7392f28d2349d95dead4c2e2c2ace2a to your computer and use it in GitHub Desktop.
Save mra-dev/d7392f28d2349d95dead4c2e2c2ace2a to your computer and use it in GitHub Desktop.
JavaScript seconds to time string with format hh:mm:ss
// As the name of the function says; It converts seconds to time(clock) format. (Useful for OTP authentication)
const secondsToTime = seconds => {
let h = Math.floor(seconds / 3600).toString().padStart(2, '0'),
m = Math.floor(seconds % 3600 / 60).toString().padStart(2, '0'),
s = Math.floor(seconds % 60).toString().padStart(2, '0')
// Returns only 00:00 format if hour is not set. (optional)
if (h === '00')
return `${m}:${s}`
return `${h}:${m}:${s}`
}
export { secondsToTime }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment