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


It looked like this: Countdown Timer Example


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: 0
6 }

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 * 24
2 const HOURS = DAYS / 24
3 const MINUTES = HOURS / 60
4 const SECONDS = MINUTES / 60
5
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 values
2 const { days, hours, minutes, seconds } = millisecondsToTimeUnits(1000000)
3
4 console.log(`TIme Left: ${days}d ${hours}h ${minutes}m ${seconds}s`)

Result: Displaying one million milliseconds formatted as days, hours, minutes, seconds