Javascript seconds to time string with format hh:mm:ss
Need the time string in hh:mm:ss from seconds without any hassle? Here's a one-liner to save the day:
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:
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! 💼🕑
Navigating through edge cases
When seconds go south
For negative seconds, our previous formula would shrivel. But worry not, with a small tweak, we'll support signed outputs!
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:
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:
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:
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:
Debugging To Perfection
Test your functions to safety lock your code against silly bugs or performance hitches:
Was this article helpful?