Convert seconds to HH-MM-SS with JavaScript?
Looking to convert seconds to HH:MM:SS? Here's a compact JavaScript function for this purpose:
This toHHMMSS
function is your quick ticket to time conversion. Just plug in your seconds, and out shoots the time in HH:MM:SS format.
Exception handling: Negative or non-numeric input
In your coding journey, you would soon realize that negative seconds and non-numeric inputs are as common as cookies in a browser (pun intended 🍪). To keep our function happy, we'll handle these cases like this:
This ensures that our function is immune to errors caused by negative or non-numeric inputs. Always remember, exception handling is the "vaccine" for potential bugs.
Geek mode: Performance with minimalism
We love performance, and sometimes that means ditching the fancy Date
object and going vanilla. If you're after efficiency, here's how to do just that:
This function bypasses the Date
object altogether, offering better performance by relying on basic math operations instead. It's lightweight and lean, just like your favorite code editor.
Enhanced functionality using Moment.js
If you're dealing with time formats that exceed 24 hours or need to handle intricate time-related computations, libraries like Moment.js come in handy:
Enjoy the extra functionality of Moment.js, but be mindful of the performance cost of external libraries. Sometimes you need a pickup truck, not a semi-trailer.
Clean syntax with arrow functions and array destructuring
Arrow functions offer a more concise syntax that makes your code look cleaner. Here's how to use it:
This looks more elegant, encapsulating our time conversion logic in a fresher syntax that pleases the modern JavaScript developer.
Data validation: Accept only valid inputs
When building functions to be used by you (or others), it's always a good idea to validate inputs for type safety:
Input validation and type coercion with parseInt
ensure better function safety against mischievous inputs.
Was this article helpful?