Find Difference Between Two LocalDateTime in Java

In this post, we will see how to find difference between two LocalDateTime in Java.

Ways to find difference between two LocalDateTime in Java

There are multiple ways to find difference between two LocalDateTime in various time units such as Days, Months, Years etc.

Using LocalDateTime’s until() method

We can use LocalDateTime’s until() method to find difference between two LocalDateTime.

LocalDateTime’s until() method returns amount of time with another date in terms of given unit. You can pass specific Temporal units such as MONTHS, DAYS, SECONDS to get result in specified units.

For example:
If you want amount of seconds between two LocalDateTime, we can use following syntax:

Here is an example:

Output

Using ChronoUnit Enum

We can use ChronoUnit method to find difference between two LocalDateTime.

It intenally calls until() method to find the difference between to time units.

For example:
If you want amount of seconds between two LocalDateTime, we can use following syntax:

Here is an example:

Output

Using Duration’s between() method

We can use Duration’s between() method to find difference between two LocalDateTime.

Duration’s between() method returns amount of time with another date in terms of minutes, hours, seconds and nanoseconds. You can use toXXX() method to convert into required unit.

For example:
If you want amount of seconds between two LocalDateTime, we can use following syntax:

Here is an example:

Output

That’s all about how to find difference two LocalDateTime in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *