Home > Software > How to Convert Milliseconds to Hours, Minutes, and Seconds in JavaScript

How to Convert Milliseconds to Hours, Minutes, and Seconds in JavaScript

Anastasios Antoniadis

Share on X (Twitter) Share on Facebook Share on Pinterest Share on LinkedInTime manipulation is a common requirement in software development, particularly in JavaScript where you might be dealing with animations, timers, tracking user activities, or handling date and time inputs. Often, you might find yourself needing to convert milliseconds into more human-readable formats such …

Javascript

Time manipulation is a common requirement in software development, particularly in JavaScript where you might be dealing with animations, timers, tracking user activities, or handling date and time inputs. Often, you might find yourself needing to convert milliseconds into more human-readable formats such as hours, minutes, and seconds. Whether you’re developing a web application, a server-side application with Node.js, or working with any other JavaScript environment, understanding how to perform this conversion efficiently can be incredibly useful. This article will guide you through the process of converting milliseconds to hours, minutes, and seconds in JavaScript.

Understanding Time Units

Before diving into the conversion, it’s essential to have a clear understanding of the relationship between milliseconds, seconds, minutes, and hours:

  • 1 Second = 1,000 Milliseconds
  • 1 Minute = 60 Seconds
  • 1 Hour = 60 Minutes or 3,600 Seconds

With this knowledge, we can start converting milliseconds into the desired units.

Conversion Process

The conversion process involves dividing the total milliseconds by the number of milliseconds in an hour, minute, and second respectively, and then using the modulus operator (%) to handle the remainder and ensure that each unit rolls over correctly.

Here’s a step-by-step guide and implementation:

Step 1: Define the Total Milliseconds

First, you need to have the total milliseconds that you want to convert. For demonstration purposes, let’s use a variable:

let totalMilliseconds = 6457000; // For example, 1 hour, 47 minutes, and 37 seconds

Step 2: Convert Milliseconds to Hours, Minutes, and Seconds

To perform the conversion, follow these steps:

  1. Calculate Hours: Divide the total milliseconds by the number of milliseconds in an hour (3,600,000) and use the Math.floor() function to get a whole number of hours.
  2. Calculate Minutes: Use the modulus operator to get the remainder of milliseconds after calculating hours, divide by the number of milliseconds in a minute (60,000), and again use Math.floor() to get whole minutes.
  3. Calculate Seconds: Finally, use the modulus operator to get the remainder of milliseconds after calculating minutes, and divide by 1,000 to convert to seconds. Rounding is optional depending on whether you want a whole number of seconds or include milliseconds in the seconds count.
function convertMsToTime(duration) {
  let milliseconds = parseInt((duration % 1000) / 100),
      seconds = Math.floor((duration / 1000) % 60),
      minutes = Math.floor((duration / (1000 * 60)) % 60),
      hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

console.log(convertMsToTime(totalMilliseconds));
// Outputs: 01:47:37.0

In this function:

  • milliseconds captures the remaining milliseconds but is divided by 100 for display purposes. You can adjust this part to suit your precision needs.
  • The seconds, minutes, and hours calculations utilize the modulus operator to find remainders, effectively rolling over each unit.
  • Zero padding is applied to ensure each unit has at least two digits, improving readability.
  • The function returns a string formatted as “HH:MM:SS.m”, where “m” represents the leftover milliseconds. Adjust the return statement if you prefer a different format or precision.

Further Considerations

  • Rounding Seconds: If you don’t need millisecond precision for seconds, you can round the seconds to the nearest whole number using Math.round() instead of Math.floor().
  • Time Zones and Daylight Saving Time: When dealing with hours, be mindful of time zones and Daylight Saving Time if you’re converting milliseconds derived from date and time calculations.
  • Leveraging Date Objects: For some use cases, creating a Date object with the milliseconds and using Date methods to extract hours, minutes, and seconds might be more appropriate, especially if you’re also dealing with dates.

Conclusion

Converting milliseconds to hours, minutes, and seconds in JavaScript is a straightforward process once you understand the basic time unit relationships and the modulo operation for handling remainders. The method outlined in this article provides a flexible way to perform this conversion, essential for creating timers, logs, animations, or any feature requiring time manipulation. Whether you’re a beginner or an experienced JavaScript developer, mastering time conversions is a valuable skill in your programming toolkit.

Anastasios Antoniadis
Follow me
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x