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

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

Linda Hamilton
Release: 2024-12-27 19:58:10
Original
690 people have browsed it

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

Formatting Duration in Java using Custom Formats

Question: How can I format a duration in seconds using a pattern like H:MM:SS in Java? Existing Java utilities are geared towards formatting time, not durations.

Solution:

To format a duration without introducing external libraries, one can utilize Java's built-in Formatter class or similar shortcuts.

For example, given an integer representing the number of seconds s:

String formattedDuration = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
Copy after login

In this code:

  • s / 3600 represents the number of hours in the duration.
  • (s % 3600) / 60 represents the number of minutes remaining after the hours have been accounted for.
  • (s % 60) represents the number of seconds remaining after the minutes have been accounted for.

The d format specifiers ensure that the minutes and seconds are always formatted with two digits, adding leading zeros as needed.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template