What is Duration in Java?

Duration in Java is a part of the java.time package which represents a time-based amount of time, such as '34.5 seconds' or '2 hours'. It is used to define a duration between two points in time and can be expressed in days, hours, minutes, seconds, and nanoseconds. The Duration class is often used in conjunction with other time-based classes, such as LocalDateTime and ZonedDateTime.

Here is an example of how to use Duration in Java:

import java.time.Duration; import java.time.LocalDateTime; public class DurationExample { public static void main(String[] args) { LocalDateTime start = LocalDateTime.now(); LocalDateTime end = start.plusHours(2).plusMinutes(30); Duration duration = Duration.between(start, end); System.out.println("Duration: " + duration.toHours() + " hours and " + duration.toMinutesPart() + " minutes."); } }

Duration Java java.time time-based amount LocalDateTime ZonedDateTime