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
- Regular expression examples in JavaScript">Regular expression examples in JavaScript
- Find common items from two Arrays in JavaScript
- array-in-javascript" title="Remove Duplicate Values from an Array in JavaScript">Remove Duplicate Values from an Array in JavaScript
- Difference between let, var and const with example
- Splice and Slice array methods in 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!