Explain Codes LogoExplain Codes Logo

Javascript seconds to time string with format hh:mm:ss

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Nov 13, 2024
TLDR

Need the time string in hh:mm:ss from seconds without any hassle? Here's a one-liner to save the day:

const toTimeString = secs => new Date(secs * 1000).toISOString().substr(11, 8);

This savvy line takes your seconds, converts them into milliseconds, fits them into an ISO date format, and grabs the time part. Feed toTimeString(3661) and out pops "01:01:01"!

Unwrapping the magic of Date object

The simple function above may seem like Abra Kadabra, but let's pull back the mystical curtain. The workhorse inside is JavaScript's Date object:

let time = new Date(0); // That epic moment when time began! time.setSeconds(secs); // Fast-forward to the specified seconds let timeString = time.toISOString(); // Convert to a standardized time representation

Here, we're actually cheating time zones. The ISO string is always in UTC, making your result time-zone agnostic. No more blaming time zones for missed meetings! 💼🕑

When seconds go south

For negative seconds, our previous formula would shrivel. But worry not, with a small tweak, we'll support signed outputs!

const toSignedTimeString = secs => { const sign = secs < 0 ? "-" : ""; return sign + new Date(Math.abs(secs) * 1000).toISOString().substr(11, 8); };

Simplifying sub-hour durations

What if you wanted to discard the leading zero in durations less than an hour? Here's how you slay that zero:

const toHmsTimeString = secs => { const date = new Date(secs * 1000); return [ date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), ].map(val => String(val).padStart(2, '0')).join(':').replace(/^00:/, ''); };

That sneaky replace is the zero-zapper we need!

Parsing and formatting: Power up with utility functions

Our time string has been super helpful, but it can be a bit opaque. Let's break down the walls and expose the numbers inside:

const toCustomTimeString = secs => { const hours = Math.floor(secs / 3600).toString().padStart(2, '0'); const minutes = Math.floor((secs % 3600) / 60).toString().padStart(2, '0'); const seconds = (secs % 60).toString().padStart(2, '0'); return `${hours}:${minutes}:${seconds}`; };

With these hardworking lines, we reach in with math, yank out the hours, minutes, and seconds, then stitch them back together into a tidy hh:mm:ss format. There's padStart ensuring the numbers don't experience outfit malfunction (missing zeros!).

Expert tricks for time string

Coping with marathon durations

If your seconds could burst past 24 hours (86400 seconds), then our old friend toISOString will sadly fail 😵. Here's how you arm wrestle the hours apart:

const toLongDurationString = secs => { const hours = Math.floor(secs / 3600).toString().padStart(2, '0'); const date = new Date(secs % 86400 * 1000); return `${hours}:${date.toISOString().substr(14, 5)}`; };

Parting the time string sea

Someday you'll want to ignore everybody else and focus only on the parts that matter. With our regex handyman, that's a cakewalk:

const extractTimePart = (timeString, part) => { const parts = { hours: /^(\d{2})/, minutes: /:(\d{2}):/, seconds: /:(\d{2})$/, }; const match = timeString.match(parts[part]); return match ? match[1] : '00'; }; // Excuse me string, I'm here for the hours!

Debugging To Perfection

Test your functions to safety lock your code against silly bugs or performance hitches:

console.assert(toTimeString(3665) === "01:01:05", "Oh snap! Test failed for 3665 seconds"); console.assert(toTimeString(-3665) === "-01:01:05", "Yikes! Test failed for -3665 seconds"); console.assert(toTimeString(90061) === "25:01:01", "Red alert! Test failed for 90061 seconds"); // Always season your testing recipe with an extra pinch of edge cases!