Home >Java >javaTutorial >How to Format a Duration in H:MM:SS Format in Java?

How to Format a Duration in H:MM:SS Format in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 19:02:15930browse

How to Format a Duration in H:MM:SS Format in Java?

Formatting Durations in Java (H:MM:SS)

Question:

How can I format a duration, represented in seconds, in the H:MM:SS format in Java?

Answer:

To format a duration using the H:MM:SS pattern, you can use the following approach:

  1. Create a Formatter object: This object will handle the formatting of the duration.

    java.util.Formatter formatter = new java.util.Formatter();
  2. Use the %d modifier: This modifier specifies that the variable should be formatted as a decimal integer.

    formatter.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
  3. Append zeros for minutes and seconds: The d modifier ensures that the minutes and seconds are always formatted with two digits, even if they are less than 10.
  4. Retrieve the formatted string: Finally, retrieve the formatted duration by calling the toString() method on the formatter object.

    String formattedDuration = formatter.toString();

Example:

int seconds = 3661;
String formattedDuration = String.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60));
System.out.println(formattedDuration); // Output: 1:01:01

The above is the detailed content of How to Format a Duration in H:MM:SS Format in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn