- 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{2days: 0,3hours: 0,4minutes: 0,5seconds: 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.

1const DAYS = 1000 * 60 * 60 * 242const HOURS = DAYS / 243const MINUTES = HOURS / 604const SECONDS = MINUTES / 6056/**7* timeDifference Integer Number of milliseconds between two date or times.8*/9export const millisecondsToTimeUnits = timeDifference => ({10days: Math.floor(timeDifference / DAYS),11hours: Math.floor((timeDifference % DAYS) / HOURS),12minutes: Math.floor((timeDifference % HOURS) / MINUTES),13seconds: 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 values2const { days, hours, minutes, seconds } = millisecondsToTimeUnits(1000000)34console.log(`TIme Left: ${days}d ${hours}h ${minutes}m ${seconds}s`)