Convert seconds to minutes and hours in JavaScript
Today we will show you how to convert seconds to minutes and hours in JavaScript. In other, convert into hh mm ss from seconds.
Convert seconds to minutes and hours in JavaScript, How to convert seconds to time string format hh:mm:ss using javascript, How to convert seconds to HH-MM-SS with JavaScript, Convert seconds to time value, Seconds to hh mm ss, how to convert hours into minutes in javascript, javascript convert seconds to dd hh mm ss, convert total seconds to hours minutes seconds js, moment js convert seconds to hh mm ss, convert seconds to hours minutes seconds, js seconds to timestamp, seconds to timespan javascript, javascript timestamp to hours minutes 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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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:
1 2 | secondsToHms(1248); // Output: 20m 48s secondsToHms(9489); // Output: 2h 38m 09s |
That’s it for today.
Thank you for reading. Happy Coding!
Good