In Java, you can format a duration using the Duration
class which represents a duration of time. Here’s an example of how you can format a duration using Duration
:
import java.time.Duration;
import java.time.format.DateTimeFormatter;
public class DurationFormatter {
public static void main(String[] args) {
Duration duration = Duration.ofHours(2).plusMinutes(30).plusSeconds(20);
// format the duration
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedDuration = formatter.format(duration);
System.out.println(formattedDuration); // prints "02:30:20"
}
}
In this example, we create a Duration
object that represents 2 hours, 30 minutes, and 20 seconds. Then, we create a DateTimeFormatter
object that specifies the format we want to use for the duration (HH:mm:ss
). Finally, we format the duration using the format()
method of the formatter object and store the result in a string variable. The output will be “02:30:20”, which is the formatted duration.