Explain Codes LogoExplain Codes Logo

Convert seconds value to hours minutes seconds?

java
code-digestion
string-format
time-conversion
Nikita BarsukovbyNikita Barsukov·Nov 23, 2024
TLDR

Here's how to transform your seconds into HH:mm:ss format in a nutshell:

int sec = 3661; // Or any number of seconds you want String time = String.format("%02d:%02d:%02d", sec / 3600, (sec % 3600) / 60, sec % 60); System.out.println(time); // Prints "01:01:01". Or in otter words, "Otterly precise!"

Code breakdown: Understand what you are codifying

Let's dissect this one-line wonder and comprehend its components for better code digestion.

Blood of the Code: Variable

int sec = 3661; // Seconds waiting to be transformed

Here, sec represents your seconds. Replace 3661 with any number of seconds you want to convert.

The Mathemagician: String.format

String time = String.format("%02d:%02d:%02d", sec / 3600, (sec % 3600) / 60, sec % 60);

The String.format method is where the magic happens. The "%02d:%02d:%02d" is a template for the output, telling the code you need two digits (%02d), and to separate these digits with colons (:).

The values inserted into these placeholders are calculated like this:

  • sec / 3600: Computes the hours. Since sec is an integer, this is an integer division that discards any remainder.
  • (sec % 3600) / 60: First, (sec % 3600) calculates the remainder of the above division, which represents the leftover seconds that don't form a complete hour. Then, we divide these seconds by 60 to find the minutes.
  • sec % 60: Computes the remaining seconds after accounting for the complete hours and minutes we have found.

In the comments, always remember the // is not a pause button, it's for comments!

The Showman: System.out.println

System.out.println(time); // Beware the console, here comes the time!

Finally, we print the formatted time to the console. Feel free to replace this with your own delivery mechanism - maybe a GUI text field, an HTTP response... or a pigeon.

Alternative Avenues: Additional Ways to Serve Time

Cooking Time with a Function

To encapsulate gorey details, you can use a function:

public static String convertToHHMMSS(int seconds) { return String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, seconds % 60); }

Then, just call this conversion function whenever you need to:

System.out.println(convertToHHMMSS(3661)); // Time is served!

Watching Out for Edge Cases

By the time you never want a negative time to occur, unless you enjoy explaining why you broke physics:

public static String convertToHHMMSS(int seconds) { if (seconds < 0) { throw new IllegalArgumentException("Seconds cannot be negative, unless you have a Delorean!"); } return String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, seconds % 60); }

Level up with Java Time API

The LocalTime class from the Java Time API rises to the challenge for more complex time manipulations:

import java.time.LocalTime; public static String convertToHHMMSSJavaTime(int seconds) { LocalTime timeOfDay = LocalTime.MIN.plusSeconds(seconds); return timeOfDay.toString(); }

Bingo! Handles overflow gracefully and formats the string nicely, it does.

Handy Tips and Tricks

Keep it Simple, Programmer

BigDecimal is a big gun you don't necessarily need to bring to this knife fight. Integers are your friends when dealing with human-scale time durations.

Android Developers Assemble

For those on Android, the DateUtils.formatElapsedTime(long) method is a shortcut worth considering.

Formatting: Consistency is Key

Ensure consistency in your timings by always formatting single-digit numbers with a leading zero. That's "%02d" in the String.format.

Testing: Or, How to Sleep at Night

Never overlook unit testing. It exposes your logic to various inputs and ensures your behaviors are as expected. This might save you time later - which, ironically, you now know how to calculate!