Duration.between: Computing Time Differences
What you'll learn: How to calculate the precise time difference between two temporal objects using Duration.between().
The Core Idea
While static factory methods like ofHours() let you create durations from scratch, Duration.between() lets you measure the actual time elapsed between two points. This is essential when you need to know "how much time passed?" rather than "create a 5-hour duration."
How Duration.between Works
The Duration.between() method accepts two Temporal objects and computes the duration from the first to the second:
Instant start = Instant.parse("2024-01-15T10:00:00Z");
Instant end = Instant.parse("2024-01-15T14:30:00Z");
Duration elapsed = Duration.between(start, end);
System.out.println(elapsed.toHours()); // 4
System.out.println(elapsed.toMinutes()); // 270
Works with Multiple Temporal Types
You can use Duration.between() with Instant, LocalTime, and LocalDateTime:
LocalTime morning = LocalTime.of(9, 0);
LocalTime afternoon = LocalTime.of(17, 30);
Duration workDay = Duration.between(morning, afternoon);
System.out.println(workDay.toHours()); // 8
LocalDateTime meetingStart = LocalDateTime.of(2024, 1, 15, 14, 0);
LocalDateTime meetingEnd = LocalDateTime.of(2024, 1, 15, 15, 45);
Duration meetingLength = Duration.between(meetingStart, meetingEnd);
System.out.println(meetingLength.toMinutes()); // 105
Direction Matters
The order of arguments determines the sign. If the end is before the start, you get a negative duration:
Duration backwards = Duration.between(afternoon, morning);
System.out.println(backwards.toHours()); // -8
Key Takeaway: Duration.between() calculates the time-based difference between two temporal objects, returning a positive duration when moving forward in time and negative when moving backward.