Java 8: Difference between two LocalDateTime in multiple units
To find the difference between two LocalDateTime
objects in multiple units, you can use the Duration
class. Here's an example of how you can use Duration
to find the difference between two LocalDateTime
objects in days, hours, and minutes:
LocalDateTime start = LocalDateTime.of(2020, Month.JANUARY, 1, 0, 0);
LocalDateTime end = LocalDateTime.of(2020, Month.JANUARY, 3, 12, 30);
Duration duration = Duration.between(start, end);
long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
System.out.println("Days: " + days);
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
This will print the following output:
Days: 2 Hours: 36 Minutes: 2190
You can also use the Period
class to find the difference between two LocalDateTime
objects in years, months, and days. Here's an example of how you can use Period
:
LocalDateTime start = LocalDateTime.of(2020, Month.JANUARY, 1, 0, 0);
LocalDateTime end = LocalDateTime.of(2022, Month.JANUARY, 3, 12, 30);
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
System.out.println("Years: " + years);
System.out.println("Months: " + months);
System.out.println("Days: " + days);
This will print the following output:
Years: 2 Months: 0 Days: 2
I hope this helps! Let me know if you have any questions.