How to convert seconds to time string using Moment.js
In this article, we will convert seconds to time string such as 10d 11h 44m 10s
or 5h 10m 49s
using Moment.js. Additionally, we need to use the moment-duration-format plugin to convert seconds to a time string.
Checkout more articles on JavaScript
Steps to convert seconds to time string
1. Import the libraries
Let’s import the moment-duration-format plugin along with the Moment.js library. Use the following scripts to convert the seconds to time string.
1 2 3 4 5 | <!-- Moment.js library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <!-- moment-duration-format plugin --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> |
If you are using the NPM Package then add the following code in the page.
1 2 3 4 | import moment from "moment-timezone"; import momentDurationFormatSetup from "moment-duration-format"; momentDurationFormatSetup(moment); |
2. Use the script
After importing the libraries, use the following script to get the desired output.
1 2 3 4 5 6 7 8 9 10 | <script> function getTimeStr(seconds) { var duration = moment.duration(seconds, 'seconds'); return duration.format("d[d] h[h] m[m] s[s]"); } console.log(getTimeStr(386090)); // Output: 4d 11h 14m 50s console.log(getTimeStr(58372)); // Output: 16h 12m 52s console.log(getTimeStr(4583)); // Output: 1h 16m 23s console.log(getTimeStr(883)); // Output: 14m 43s |
3. Output
Let’s combine the above code together and see how it works. You will see the output in the console.
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 30 31 32 33 34 35 36 37 38 39 | <!DOCTYPE html> <html lang="en"> <head> <title>How to convert seconds to time string using Moment.js - Clue Mediator</title> <!-- Moment.js library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <!-- moment-duration-format plugin --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> <style> body { font-family: Arial, Helvetica, sans-serif; } </style> </head> <body> <h3>How to convert seconds to time string using Moment.js - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h3> <p>Check console logs to get the formatted time string.</p> <script> function getTimeStr(seconds) { var duration = moment.duration(seconds, 'seconds'); return duration.format("d[d] h[h] m[m] s[s]"); } console.log(getTimeStr(386090)); // Output: 4d 11h 14m 50s console.log(getTimeStr(58372)); // Output: 16h 12m 52s console.log(getTimeStr(4583)); // Output: 1h 16m 23s console.log(getTimeStr(883)); // Output: 14m 43s </script> </body> </html> |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂