Java Duration class

The Duration class is part of the Java 8 java.time package, which provides a modern date and time API. It represents a duration of time, such as “2 hours and 30 minutes”, without any reference to a specific date or time zone.

Here is an example of how to create a Duration object that represents 2 hours and 30 minutes:

Duration duration = Duration.ofHours(2).plusMinutes(30);

You can also create a Duration object from a number of seconds or nanoseconds:

Duration duration = Duration.ofSeconds(300); // 5 minutes
Duration duration = Duration.ofNanos(2_500_000_000L); // 2.5 seconds

Once you have a Duration object, you can perform various operations on it. For example, you can add or subtract durations, or convert them to different units:

Duration duration1 = Duration.ofHours(1);
Duration duration2 = Duration.ofMinutes(30);
Duration totalDuration = duration1.plus(duration2); // 1 hour and 30 minutes

long minutes = totalDuration.toMinutes(); // 90
long seconds = totalDuration.getSeconds(); // 5400

Duration halfDuration = totalDuration.dividedBy(2); // 45 minutes

The Duration class also has various methods for comparing durations:

Duration duration1 = Duration.ofMinutes(30);
Duration duration2 = Duration.ofMinutes(45);

int comparisonResult = duration1.compareTo(duration2); // -1
boolean isEqual = duration1.equals(duration2); // false

Overall, the Duration class is a useful tool for representing and manipulating durations of time in Java.

Java Duration class declaration:

The Duration class is part of the java.time package in Java 8 and later versions. Here is the declaration of the Duration class:

public final class Duration
    implements TemporalAmount, Comparable<Duration>, Serializable

The Duration class is a final class, which means it cannot be extended. It implements the TemporalAmount interface, which represents a duration of time in a generic way that can be used with other date and time classes in the java.time package.

The Duration class also implements the Comparable interface, which allows Duration objects to be compared with each other.

Duration objects are immutable, which means that once they are created, their value cannot be changed.

The Duration class provides various methods for creating and manipulating durations of time, such as:

  • ofDays(long days)
  • ofHours(long hours)
  • ofMinutes(long minutes)
  • ofSeconds(long seconds)
  • ofMillis(long millis)
  • ofNanos(long nanos)
  • plus(Duration durationToAdd)
  • minus(Duration durationToSubtract)
  • dividedBy(long divisor)
  • compareTo(Duration otherDuration)
  • equals(Object other)
  • toDays()
  • toHours()
  • toMinutes()
  • toSeconds()
  • toMillis()
  • toNanos()

These methods allow you to create Duration objects of different lengths, add or subtract durations, divide durations by a number, compare durations with each other, and convert durations to different units.

Methods of Java Duration:

The Duration class in Java provides several methods to manipulate and obtain information about a duration of time. Here are some of the most commonly used methods:

  1. ofXXX() Methods:
    • ofDays(long days) – creates a Duration object with the specified number of days.
    • ofHours(long hours) – creates a Duration object with the specified number of hours.
    • ofMinutes(long minutes) – creates a Duration object with the specified number of minutes.
    • ofSeconds(long seconds) – creates a Duration object with the specified number of seconds.
    • ofMillis(long millis) – creates a Duration object with the specified number of milliseconds.
    • ofNanos(long nanos) – creates a Duration object with the specified number of nanoseconds.
  2. plus() and minus() Methods:
    • plus(Duration durationToAdd) – adds the specified duration to the current duration and returns a new Duration object.
    • plus(long amountToAdd, TemporalUnit unit) – adds the specified amount of time to the current duration and returns a new Duration object.
    • minus(Duration durationToSubtract) – subtracts the specified duration from the current duration and returns a new Duration object.
    • minus(long amountToSubtract, TemporalUnit unit) – subtracts the specified amount of time from the current duration and returns a new Duration object.
  3. dividedBy() and multipliedBy() Methods:
    • dividedBy(long divisor) – divides the current duration by the specified divisor and returns a new Duration object.
    • multipliedBy(long multiplicand) – multiplies the current duration by the specified multiplicand and returns a new Duration object.
  4. compareTo() and equals() Methods:
    • compareTo(Duration otherDuration) – compares the current duration with the specified duration and returns a value indicating the order.
    • equals(Object other) – compares the current duration with the specified object and returns true if they represent the same duration.
  5. getXXX() and toXXX() Methods:
    • get(TemporalUnit unit) – gets the value of the specified unit of the duration.
    • toDays() – returns the number of days in the duration.
    • toHours() – returns the number of hours in the duration.
    • toMinutes() – returns the number of minutes in the duration.
    • toSeconds() – returns the number of seconds in the duration.
    • toMillis() – returns the number of milliseconds in the duration.
    • toNanos() – returns the number of nanoseconds in the duration.

These methods allow you to create, manipulate, and obtain information about durations of time in Java.

Java Duration Example: get()

Sure! Here’s an example of using the get() method in the Duration class:

import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class DurationExample {
    public static void main(String[] args) {
        Duration duration = Duration.ofHours(3).plusMinutes(30);

        long hours = duration.get(ChronoUnit.HOURS);
        long minutes = duration.get(ChronoUnit.MINUTES);

        System.out.println("Duration: " + duration);
        System.out.println("Hours: " + hours);
        System.out.println("Minutes: " + minutes);
    }
}

In this example, we create a Duration object with a value of 3 hours and 30 minutes using the ofHours() and plusMinutes() methods. We then use the get() method to extract the number of hours and minutes from the Duration object.

The get() method takes a TemporalUnit argument that specifies the unit of time to extract from the Duration. In this case, we use the ChronoUnit.HOURS and ChronoUnit.MINUTES constants to extract the number of hours and minutes, respectively.

When we run this program, the output will be:

Duration: PT3H30M
Hours: 3
Minutes: 30

This shows that the get() method can be used to extract specific units of time from a Duration object.

Java Duration Example: isNegative()

Certainly! Here’s an example of using the isNegative() method in the Duration class:

import java.time.Duration;

public class DurationExample {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofSeconds(-30);
        Duration duration2 = Duration.ofMinutes(2);

        System.out.println("Duration 1: " + duration1);
        System.out.println("Is duration 1 negative? " + duration1.isNegative());

        System.out.println("Duration 2: " + duration2);
        System.out.println("Is duration 2 negative? " + duration2.isNegative());
    }
}

In this example, we create two Duration objects: duration1 with a value of negative 30 seconds using the ofSeconds() method, and duration2 with a value of 2 minutes using the ofMinutes() method. We then use the isNegative() method to check if each duration is negative or not.

When we run this program, the output will be:

Duration 1: PT-30S
Is duration 1 negative? true
Duration 2: PT2M
Is duration 2 negative? false

This shows that the isNegative() method can be used to determine if a Duration object represents a negative duration or not. In this case, duration1 is negative and duration2 is not.

Java Duration Example: between()

Certainly! Here’s an example of using the between() method in the Duration class:

import java.time.Duration;
import java.time.LocalDateTime;

public class DurationExample {
    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2023, 5, 1, 12, 0);
        LocalDateTime end = LocalDateTime.of(2023, 5, 2, 15, 30);
        
        Duration duration = Duration.between(start, end);
        System.out.println("Duration between " + start + " and " + end + ": " + duration);
    }
}

In this example, we create two LocalDateTime objects: start with a value of May 1st, 2023 at 12:00 PM, and end with a value of May 2nd, 2023 at 3:30 PM. We then use the between() method to calculate the duration between these two LocalDateTime objects.

When we run this program, the output will be:

Duration between 2023-05-01T12:00 and 2023-05-02T15:30: PT27H30M

This shows that the between() method can be used to calculate the duration between two points in time. In this case, the duration is 27 hours and 30 minutes.

Java Duration Example: minus()

Sure! Here’s an example of using the minus() method in the Duration class:

import java.time.Duration;

public class DurationExample {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofMinutes(10);
        Duration duration2 = Duration.ofSeconds(30);

        Duration result = duration1.minus(duration2);
        System.out.println("Result: " + result);
    }
}

In this example, we create two Duration objects: duration1 with a value of 10 minutes using the ofMinutes() method, and duration2 with a value of 30 seconds using the ofSeconds() method. We then use the minus() method to subtract duration2 from duration1 and store the result in the result variable.

When we run this program, the output will be:

Result: PT9M30S

This shows that the minus() method can be used to subtract one Duration object from another. In this case, we subtracted 30 seconds from 10 minutes to get a result of 9 minutes and 30 seconds.

Java Duration Example: plus()

Certainly! Here’s an example of using the plus() method in the Duration class:

import java.time.Duration;

public class DurationExample {
    public static void main(String[] args) {
        Duration duration1 = Duration.ofMinutes(5);
        Duration duration2 = Duration.ofSeconds(30);

        Duration result = duration1.plus(duration2);
        System.out.println("Result: " + result);
    }
}

In this example, we create two Duration objects: duration1 with a value of 5 minutes using the ofMinutes() method, and duration2 with a value of 30 seconds using the ofSeconds() method. We then use the plus() method to add duration2 to duration1 and store the result in the result variable.

When we run this program, the output will be:

Result: PT5M30S

This shows that the plus() method can be used to add one Duration object to another. In this case, we added 30 seconds to 5 minutes to get a result of 5 minutes and 30 seconds.