# How To Convert Milliseconds To Hours, Minutes, Seconds Using JavaScript

## Convert Milliseconds To Hours, Minutes, Seconds Using JavaScript

These are some solutions that can help you convert Milliseconds to Hours, Minutes, Seconds using JavaScript. To do that, you can customize your function. Another solution is to use the module ‘moment’, which has functions built to help you convert to Hours, Minutes, Seconds, and you do not have to write your function by yourself.

### Create the function

In this method, you will create a function by yourself, and you don’t need to use some module or available functions.

Step one, you have to convert milliseconds to seconds.

Step two, you convert seconds to Hours by dividing it by 3600.

In step three, you get the residual result of step two and divide it by 60. The result is Minutes.

Finally, the residual result of step three is Seconds.

Look at the example below to know how to do it:

function convertMsToTime(ms) {

// Convert milliseconds to seconds
let s = Math.floor(ms/1000);

// Get Hours by dividing seconds by 3600
let hours = Math.floor(s/3600);
s = s - 3600*hours;

// Divide the residual result of Hours by 60 to get Minutes
let minutes = Math.floor(s/60);
s = s - 60*minutes

// The rest is the seconds
let seconds = s;

console.log('Hours: '+hours+', Minutes: '+minutes+', Seconds: '+seconds)
}

// Try the sulution you have already created
convertMsToTime(3564883)
convertMsToTime(472002000)

Output

Hours: 0, Minutes: 59, Seconds: 24
Hours: 131, Minutes: 6, Seconds: 42

### Use the moment

Using the ‘moment’ module, you will not have to create a function by yourself. You can convert Milliseconds to Hours, Minutes, Seconds by the available functions.

Here is example:

import moment from "moment";

function convertMsToTime(ms){

// Get the Hours by the asHours() method
let hours = Math.floor(moment.duration(ms,'milliseconds').asHours())

// Get the Minutes
let minutes = Math.floor(moment.duration(ms,'milliseconds').asMinutes()) - hours*60

// Get the Seconds
let seconds = Math.floor(moment.duration(ms,'milliseconds').asSeconds()) -hours*3600 - minutes*60

console.log('Hours: '+hours+', Minutes: '+minutes+', Seconds: '+seconds)
}

// Try the sulution you have already created
convertMsToTime(3564883)
convertMsToTime(472002000)

Output

Hours: 0, Minutes: 59, Seconds: 24
Hours: 131, Minutes: 6, Seconds: 42

## Summary

To convert Milliseconds to Hours, Minutes, Seconds using JavaScript, you can create your function by yourself, or you can use the ‘moment’ module, which has some available functions to help you. Choose the solution that is best for you. We hope this tutorial is helpful to you. Thanks!

Maybe you are interested: