It represents a time-based amount of time such as `34.5seconds`, `2 hours`. It deals with quantity of time with seconds and nanoseconds precision as well. In addition, DAYS unit can be used and it is treated like 24 hours amount of time, without considering any daylight saving effects. For date based amounts of time one can use java.time.Period class.
Duration class is immutable class and thread-safe. Duration class has static factory methods ofDays(), ofHours(), ofMinutes(), ofSeconds(), ofMillis(), and ofNanos() like for Duration instance creation.
import java.time.Duration;
import java.time.LocalDateTime;
public class DurationExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = LocalDateTime.of(2025, 10, 13, 22, 52, 0);
System.out.println("Current date time: " + now);
//30 minutes amount of time
Duration duration = Duration.between(now, then);
System.out.println("Duration between now and then " + duration);
//add 10 hours and 2 minutes for the duration
Duration changedDuration = duration.plusHours(10).plusMinutes(2);
System.out.println("changed duration : " + changedDuration);
Duration lessDuration = Duration.ofSeconds(30);
//convert duration to nanoseconds and millis
System.out.println("less duration in nanos : " + lessDuration.toNanos());
System.out.println("less duration in millis : " + lessDuration.toMillis());
}
}
Result:
Current date time: 2025-10-13T21:55:26.190489700
Duration between now and then PT56M33.8095103S
changed duration : PT10H58M33.8095103S
No comments:
Post a Comment