Explain Codes LogoExplain Codes Logo

Convert seconds to HH-MM-SS with JavaScript?

javascript
exception-handling
performance
functions
Alex KataevbyAlex Kataev·Dec 17, 2024
TLDR

Looking to convert seconds to HH:MM:SS? Here's a compact JavaScript function for this purpose:

function toHHMMSS(secs) { const pad = val => ('0' + val).slice(-2); return [Math.floor(secs / 3600), Math.floor((secs % 3600) / 60), secs % 60] .map(pad) .join(':'); } console.log(toHHMMSS(3665)); // Outputs "01:01:05". Time wizardry done right!

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:

function toHHMMSS(secs) { if (typeof secs !== 'number' || isNaN(secs)) { throw new Error('Expected a number, but got a cookie instead.'); } if (secs < 0) { throw new Error('Negative seconds, is time travelling a thing now?'); } // Time magic continues here... }

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:

function toHHMMSS(secs) { const pad = val => String(val).padStart(2, '0'); return [Math.floor(secs / 3600), Math.floor((secs % 3600) / 60), secs % 60] .map(pad) .join(':'); } console.log(toHHMMSS(7265)); // Again, "02:01:05". Fast as Flash now!

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:

function toHHMMSS(secs) { return moment.utc(secs * 1000).format('HH:mm:ss'); } console.log(toHHMMSS(90000)); // Gives "25:00:00". We have created a 25-hour day!

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:

const toHHMMSS = secs => { const [hh, mm, ss] = [3600, 60, 1].map(unit => String(Math.floor(secs / unit % 60)).padStart(2, '0')); return [hh.trim(), mm, ss].join(':'); }; console.log(toHHMMSS(7265)); // Outputs "02:01:05". Fancy and clean, just like your Sunday's best.

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:

function toHHMMSS(secs) { const seconds = parseInt(secs, 10); if (isNaN(seconds)) { throw new TypeError('Expected the seconds count, but got a cookie recipe instead.'); } // Time magic continues here... }

Input validation and type coercion with parseInt ensure better function safety against mischievous inputs.