How to convert seconds to minutes and hours in JavaScript
📅July 13, 2021
Today we will show you how to convert seconds to minutes and hours in JavaScript. In other words, convert into hh mm ss from seconds.
- How to Get current Date & Time in JavaScript
- Validate the value by regular expression in JavaScript
- Sorting an array in JavaScript
- How to compare two dates in JavaScript
- JavaScript array methods Push, Pop, Shift and Unshift
Let’s take an example, where you want to convert for example 1248 seconds to 20m 48s.
If the converted time is more than 1 hours for example 9489 seconds then it should be 2h 38m 09s.
Function
Following function will return the converted value from the seconds to hh mm ss.
function secondsToHms(seconds) {
if (!seconds) return '';
let duration = seconds;
let hours = duration / 3600;
duration = duration % (3600);
let min = parseInt(duration / 60);
duration = duration % (60);
let sec = parseInt(duration);
if (sec < 10) {
sec = `0${sec}`;
}
if (min < 10) {
min = `0${min}`;
}
if (parseInt(hours, 10) > 0) {
return `${parseInt(hours, 10)}h ${min}m ${sec}s`
}
else if (min == 0) {
return `${sec}s`
}
else {
return `${min}m ${sec}s`
}
}
Output
secondsToHms(1248); // Output: 20m 48s
secondsToHms(9489); // Output: 2h 38m 09s
That’s it for today.
Thank you for reading. Happy Coding!