How do I use java.time.Duration class?

java.time.Duration is another useful class in Java for dealing with time. It measures time in seconds and nanoseconds and is most suitable for smaller amounts of time, like “20 seconds” or “3 hours”, and not for larger units like “3 days” or “4 months”. Here’s a guide on how to use it:

1. Creating a Duration instance

You can create an instance of Duration using one of its static factory methods that best suits your needs, such as ofSeconds(), ofMinutes(), ofHours(), or ofMillis().

//create a duration of 60 seconds
Duration duration = Duration.ofSeconds(60);

//create a duration of 2 hours
Duration twoHours = Duration.ofHours(2);

2. Creating a Duration between two Instants

Duration also provides a static method between() that can be used to find the duration between two points in time.

Instant start = Instant.now();
// Do some time consuming task...
Instant end = Instant.now();

Duration duration = Duration.between(start, end);

3. Retrieving the Duration

You can retrieve the number of days, hours, minutes, or seconds in a Duration using methods like toDays(), toHours(), toMinutes(), or getSeconds().

long hours = twoHours.toHours();  // returns 2

4. Adding and Subtracting from a Duration

Duration can be added or subtracted from another using the plus() and minus() methods or the more specific plus / minus methods such as plusHours(), minusMinutes(), etc.

// Adding
Duration additionalDuration = duration.plusHours(4);

// Subtracting
Duration lessDuration = additionalDuration.minusMinutes(50);

5. Comparing Durations

The Duration class provides compareTo(), equals(), negated(), and abs() methods for comparison:

Duration duration1 = Duration.ofHours(4);
Duration duration2 = Duration.ofHours(2);

// Returns a negative number, zero, or positive number if less than, 
// equal to, or greater than the other.
int comparison = duration1.compareTo(duration2);

boolean equals = duration1.equals(duration2); // false

// Returns a duration with the new duration being negative of this 
// duration.
Duration negated = duration1.negated(); 

// Returns a duration with the new duration being absolute of 
// this duration, effectively, it returns the same as duration1.
Duration abs = negated.abs(); 

How do I find the difference between two times?

The following code snippet show you how to find the difference between two time objects represented by LocalTime class. To get the difference between two LocalTime objects we can use the Duration.between() method. This method returns a Duration object, to get the difference in seconds we call the getSeconds() method.

Here a code snippet to demonstrate it.

package org.kodejava.datetime;

import java.time.*;

public class TimeDifference {
    public static void main(String[] args) {
        LocalTime start = LocalTime.now();
        LocalTime end = LocalTime.of(16, 59, 55);
        Duration duration = Duration.between(start, end);

        System.out.printf("Seconds between %s and %s is: %s seconds.%n",
                start, end, duration.getSeconds());

        diffLocalDateTime();
        diffInstant();
    }

    /**
     * Difference between two LocalDateTime objects.
     */
    public static void diffLocalDateTime() {
        LocalDateTime dt1 = LocalDateTime.now();
        LocalDateTime dt2 = LocalDateTime.now(ZoneId.of("GMT+0"));
        Duration duration = Duration.between(dt1, dt2);
        System.out.printf("Duration = %s seconds.%n", duration.getSeconds());
    }

    /**
     * Difference between two Instant objects.
     */
    public static void diffInstant() {
        Instant instant1 = Instant.now();
        Instant instant2 = Instant.EPOCH;
        Duration duration = Duration.between(instant1, instant2);
        System.out.printf("Duration = %s seconds.%n", duration.getSeconds());
    }
}

Using the Duration.between() we can also get the difference between two LocalDateTime objects and two Instant object as seen in the diffLocalDateTime() method and diffInstant method in the code snippet above.

The result of the code snippet:

Seconds between 15:05:35.401317900 and 16:59:55 is: 6859 seconds.
Duration = -28800 seconds.
Duration = -1637132736 seconds.