- JavaScript

June 26, 2020 • 1 min read

A while back I was working on a feature for a project I built to display a countdown. I wanted the countdown to display the number of days, hours, minutes, and seconds left until the user had to take an action. The countdown would update every second and be displayed to the user.

To get the updated time values, the calculation for it needs to run after a certain timeout period. In
this case it will be one second. By using the time difference in milliseconds between two dates or times, we can implement the function
to provide the time values we are looking for. We will call this function `millisecondsToTimeUnits`

.

- Takes a parameter,
**timeDifference**, which is an integer value representing the number of milliseconds between two dates or times. - Since we want to display
**days, hours, minutes, and seconds**, we will return an object containing the value of each. Example:

1 {2 days: 0,3 hours: 0,4 minutes: 0,5 seconds: 06 }

The implementation follows this algorithm.

- For the largest time unit:
- Convert the
**timeDifference**to the current time unit - Take the
`floor`

of the result

- Convert the
- For the next smaller time unit:
- Use the remainder of the previous calculation to convert to the current time unit
- Take the
`floor`

of the result

- Repeat step 2 until all time units have been calculated

Here is the result.

1 const DAYS = 1000 * 60 * 60 * 242 const HOURS = DAYS / 243 const MINUTES = HOURS / 604 const SECONDS = MINUTES / 6056 /**7 * timeDifference Integer Number of milliseconds between two date or times.8 */9 export const millisecondsToTimeUnits = timeDifference => ({10 days: Math.floor(timeDifference / DAYS),11 hours: Math.floor((timeDifference % DAYS) / HOURS),12 minutes: Math.floor((timeDifference % HOURS) / MINUTES),13 seconds: Math.floor((timeDifference % MINUTES) / SECONDS),14 })

With the implementation we have, it makes formatting the countdown timer really easy.

1 // Use object destructuring to get the individual values2 const { days, hours, minutes, seconds } = millisecondsToTimeUnits(1000000)34 console.log(`TIme Left: ${days}d ${hours}h ${minutes}m ${seconds}s`)