How to find the difference between two LocalDateTime objects?

In the previous post, How do I find the difference between two times?, we get the difference between two LocalTime objects in seconds measurement. In this example we will get the difference between two LocalDateTime objects and get the difference between these objects in years, months, days, hours, minutes, seconds and milliseconds.

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeDiff {
    public static void main(String[] args) {
        LocalDateTime from = LocalDateTime.of(2021, Month.JANUARY, 10, 10, 0, 30);
        LocalDateTime to = LocalDateTime.now();

        LocalDateTime fromTemp = LocalDateTime.from(from);
        long years = fromTemp.until(to, ChronoUnit.YEARS);
        fromTemp = fromTemp.plusYears(years);

        long months = fromTemp.until(to, ChronoUnit.MONTHS);
        fromTemp = fromTemp.plusMonths(months);

        long days = fromTemp.until(to, ChronoUnit.DAYS);
        fromTemp = fromTemp.plusDays(days);

        long hours = fromTemp.until(to, ChronoUnit.HOURS);
        fromTemp = fromTemp.plusHours(hours);

        long minutes = fromTemp.until(to, ChronoUnit.MINUTES);
        fromTemp = fromTemp.plusMinutes(minutes);

        long seconds = fromTemp.until(to, ChronoUnit.SECONDS);
        fromTemp = fromTemp.plusSeconds(seconds);

        long millis = fromTemp.until(to, ChronoUnit.MILLIS);

        System.out.println("From = " + from);
        System.out.println("To   = " + to);
        System.out.printf("The difference is %s years, %s months, %s days, " +
                        "%s hours, %s minutes, %s seconds, %s millis",
                years, months, days, hours, minutes, seconds, millis);
    }
}

The result of the code snippet above when executed is:

From = 2021-01-10T10:00:30
To   = 2021-11-17T15:07:37.913247900
The difference is 0 years, 10 months, 7 days, 5 hours, 7 minutes, 7 seconds, 913 millis
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.