Skip to main content

Posts

Showing posts from March, 2024

Filter time in JavaScript to a Digital Clock Format: Hh Mm Ss

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: function digitalClockTime (totalSeconds) {        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 ho...