• JavaScript

# How to get days, hours, minutes, and seconds from milliseconds

June 26, 2020 • 1 min read

## Use this to show users a countdown or a timer. ⏰

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`.

# Requirements

• 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 }`

# Implementation

The implementation follows this algorithm.

1. For the largest time unit:
• Convert the timeDifference to the current time unit
• Take the `floor` of the result
2. 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
3. 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 / 605 6 /**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 })`

## Let's use it

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)3 4 console.log(`TIme Left: \${days}d \${hours}h \${minutes}m \${seconds}s`)`