Find Difference Between Two Instant in Java

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

Ways to find difference between two Instant in Java

There are multiple ways to find difference between two Instant in various time units such as Days, Hours, Minutes, Seconds etc.

Using Instant’s until() method

To find difference between two Instant, We can use Instant’s until() method.

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

For example:
If you want amount of seconds between two Instant, you can use below code:

Here is an example:

Output

Using ChronoUnit Enum

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

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

For example:
If you want amount of seconds between two Instant, 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 Instant.

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 Instant, we can use following syntax:

Here is an example:

Output

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

Was this post helpful?

Leave a Reply

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