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

References

  1. Class LocalDateTime
  2. Class Duration
  3. How to calculate difference between two dates in Java

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.