Java 8 – Calculate difference between two LocalDateTime
In this short article, we’ll learn how to calculate the difference between two dates in Java 8. We can use the Duration
class of Time API to calculate the difference between two LocalDateTime
.
LocalDateTimeDiff.java
package org.websparrow;
import java.time.Duration;
import java.time.LocalDateTime;
public class LocalDateTimeDiff {
public static void main(String[] args) {
LocalDateTime dateTime1 = LocalDateTime.of(1991, 12, 9, 1, 20, 22);
LocalDateTime dateTime2 = LocalDateTime.of(2020, 6, 28, 9, 18, 55);
Duration diff = Duration.between(dateTime1, dateTime2);
// days between datetime 1 and datetime 2
System.out.println("Days: " + diff.toDays());
// hours between datetime 1 and datetime 2
System.out.println("Hours: " + diff.toHours());
// Minutes between datetime 1 and datetime 2
System.out.println("Minutes: " + diff.toMinutes());
// Seconds between datetime 1 and datetime 2
System.out.println("Seconds: " + diff.getSeconds());
}
}
Console
Days: 10429
Hours: 250303
Minutes: 15018238
Seconds: 901094313