Problem:
I needed to convert seconds to a time format easily read by humans. I thought a digital time format would give the best user experience. The filtered time would look something like this:
2h 46m 12s
Solution:
Here's a JavaScript function i created that solves our time format problem:
const hours = Math.floor(totalSeconds / 60 / 60)
totalSeconds = (totalSeconds - (hours * 60 * 60))
const minutes = Math.floor(totalSeconds / 60)
totalSeconds = (totalSeconds - (minutes * 60))
const seconds = totalSeconds
const timeParts = []
if (hours) { timeParts.push(`${hours}h`) }
if (minutes) { timeParts.push(`${minutes}m`) }
if (seconds) { timeParts.push(`${seconds}s`) }
return timeParts.join(' ')
}
console.log(digitalClockTime(5020))
I basically took the total seconds passed to digitalClockTime and calculated the rounded hours, and from the rounded down hours, get the rounded down minutes and leftover seconds. Nothing special here.
What I didn't want to do is show any hour, minute or seconds if set to 0. I created an array that only contained time parts > 0, then converted the array to a string and returned the result.
Let me know if this helps you as it did me!
Comments
Post a Comment