Home > Java > javaTutorial > How Can I Format a Duration in Java as H:MM:SS?

How Can I Format a Duration in Java as H:MM:SS?

Barbara Streisand
Release: 2024-12-21 08:36:12
Original
835 people have browsed it

How Can I Format a Duration in Java as H:MM:SS?

Formatting Durations in Java as H:MM:SS

In Java, the existing time formatting utilities are primarily focused on formatting timestamps rather than durations. To format durations effectively, you can employ a straightforward approach using a Formatter or related shortcuts.

For instance, given an integer representing seconds (s), you can format it into the desired H:MM:SS format using the following pattern:

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

In this expression:

  • s / 3600: Calculates the number of hours
  • (s % 3600) / 60: Determines the number of minutes
  • (s % 60): Obtains the number of seconds

By utilizing this approach, you can conveniently format durations into the H:MM:SS pattern without introducing external libraries into your Java code.

The above is the detailed content of How Can I Format a Duration in Java as H:MM:SS?. 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