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.
Checkout more articles on JavaScript
Example
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!