Updated June 20, 2023
Introduction to Java Duration
Duration in java is a class used to measure time in seconds and nanoseconds. The package of the duration class in java is java.time.Duration. The Duration class object specifies the period of time or is used to determine the difference between two times. A Duration object is immutable and thread-safe also as the Duration object is immutable, so we cannot change its values once it is created. But, we can create new Duration objects based on another Duration object. The Duration class inherits an object class ( as an object is the superclass of all classes in java) and implements the Comparable interface.
Syntax
The syntax of the Duration class declaration in java is:
public final class Duration extends Object implements Comparable < Duration >,
TemporalAmount, Serializable
{
//
variables and method of the class Duration}
Lists of Duration
The lists of Duration class methods are explained below with example code; an example code can be used further for similar methods (as for each method example code not given):
- Duration abs(): This method returns a copy of this duration with a positive length.
- long get(TemporalUnit unit): Return the value of the requested unit.
- static duration between(Temporal startInclusive, Temporal endExclusive): Return duration object, which is the duration between two temporal objects.
Example #1
We understand the above methods with the below sample java code.
Code:
package p1;
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.MAX,LocalTime.MIN);
System.out.println(d.get(ChronoUnit.SECONDS));
Duration absd = d.abs();
System.out.println(absd.get(ChronoUnit.SECONDS));
}
}
Output:
- Temporal addTo(Temporal temporal): Return duration object, which is the addition of temporal and this duration object.
- Duration dividedBy(long divisor): Return the duration object, which is this duration divided by the divisor.
Example #2
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.MAX,LocalTime.MIN);
LocalDateTime date = LocalDateTime.now();
System.out.println(date);
date = (LocalDateTime)d.addTo(date);
System.out.println(date);
Duration d1 = d.dividedBy(4);
System.out.println(d1);
System.out.println(d.getSeconds());
System.out.println(d1.getSeconds());
}
}
Output:
- int compareTo(Duration otherDuration): This duration and specified duration compares.
- boolean equals(Object otherDuration): Checks this duration with specified Duration and returns Boolean.
- boolean isNegative(): Return True if this duration is negative.
- boolean isZero(): Return True if this duration length is zero.
Example #3
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX);
Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MIN);
System.out.println(d1.getSeconds());
System.out.println(d.compareTo(d1));
System.out.println(d1.compareTo(d1));
System.out.println(d1.compareTo(d));
System.out.println(d1.equals(d));
System.out.println(d1.isNegative());
System.out.println(d1.isZero());
}
}
Output:
- static duration from(TemporalAmount amount): Obtains an instance of duration from a temporal amount.
Example #4
We understand the above method with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.from(ChronoUnit.DAYS.getDuration());
System.out.println(d.toMinutes());
}
}
Output:
- int getNano(): Return duration in nanoseconds.
- long getSeconds(): Return duration in seconds.
- List<TemporalUnit> getUnits(): Return set of units supported by this duration.
- int hashCode(): Return hash code for this duration.
Example #5
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX);
System.out.println(d.getUnits());
System.out.println(d.toMinutes());
System.out.println(d.getSeconds());
System.out.println(d.getNano());
System.out.println(d.getClass());
}
}
Output:
- Duration minus(Duration duration):- Returns object which results from this duration subtracted with the specified duration.
- Duration minus(long amountToSubtract, TemporalUnit unit): Returns object resulting from this duration subtracted with the specified duration.
- Duration minusDays(long daysToSubtract): Returns object which results from this duration subtracted with the specified duration in standard 24-hour days.
- Duration minusHours(long hoursToSubtract): Returns object resulting from this duration subtracted with the specified duration in hours.
- Duration minusMillis(long millisToSubtract): Returns object resulting from this duration subtracted with the specified duration in milliseconds.
- Duration minusMinutes(long minutesToSubtract): Returns object resulting from this duration subtracted with the specified duration in minutes.
- Duration minusNanos(long nanosToSubtract): Returns object resulting from this duration subtracted with the specified duration in nanoseconds.
- Duration minusSeconds(long secondsToSubtract): Returns object resulting from this duration subtracted with the specified duration in seconds.
- Duration multipliedBy(long multiplicand): Returns object resulting from this duration multiplied by the scalar.
- Duration negated() – Returns object which results from this duration with the length negated.
- static duration of(long amount, TemporalUnit unit): Returns Duration object representing an amount in the specified unit.
- static Duration ofDays(long days): Returns Duration object of standard 24-hour days.
- static Duration ofHours(long hours): Returns Duration object of the hour.
- static Duration ofMillis(long millis): Returns Duration object of milliseconds.
- static Duration ofMinutes(long minutes): Returns Duration object of minutes.
- static Duration ofNanos(long nanos): Returns Duration object of nanoseconds.
- static Duration ofSeconds(long seconds): Returns Duration object of seconds.
- static Duration ofSeconds(long seconds, long nanoAdjustment): Returns Duration object of seconds and nanoseconds adjustment.
Example #6
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.getSeconds());
Duration d1 = d.minusDays(3);
System.out.println(d1.getSeconds());
d = Duration.ofHours(6);
System.out.println(d.getSeconds());
d1 = d.minusHours(2);
System.out.println(d1.getSeconds());
}
}
Output:
- static Duration parse(CharSequence text): Return duration object from a text, for example, PnDTnHnMn.nS.
- Duration plus(Duration duration): Return the duration object of this duration with added the specified duration.
- Duration plus(long amountToAdd, TemporalUnit unit): Return the duration object of this duration with add the specified duration.
- Duration plusDays(long daysToAdd): Return the duration object of this duration with add the specified duration in 24-hour days.
- Duration plusHours(long hoursToAdd): Return the duration object of this duration with add the specified duration in hours.
- Duration plusMillis(long millisToAdd): Return the duration object of this duration with add the specified duration in milliseconds.
- Duration plusMinutes(long minutesToAdd): Return the duration object of this duration with the add specified duration in minutes.
- Duration plusNanos(long nanosToAdd): Return the duration object of this duration with add the specified duration in nanoseconds.
- Duration plusSeconds(long secondsToAdd): Return the duration object of this duration with the specified duration in seconds.
Example #7
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.getSeconds());
Duration d1 = d.plusDays(2);
System.out.println(d1.getSeconds());
d = Duration.ofHours(6);
System.out.println(d.getSeconds());
d1 = d.plusHours(2);
System.out.println(d1.getSeconds());
}
}
Output:
- Temporal subtractFrom(Temporal temporal): Return Subtraction of this duration from the temporal object.
- long toDays(): Return the number of days in this duration.
- long toHours(): Return the number of hours in this duration.
- long toMillis(): Return the number of milliseconds in this duration.
- long toMinutes(): return the number of minutes in this duration.
- long toNanos(): return the number of nanoseconds in this duration.
- String toString(): Return this duration in string representation, such as PT8H6M12.345S.
Example #8
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.toHours());
Duration d1 =Duration.ofHours(24) ;
System.out.println(d1.toDays());
}
}
Output:
- Duration withNanos(int nanoOfSecond): Returns duration object with the specified nanoofsecond.
- Duration withSeconds(long seconds): Returns duration object of this duration with the seconds of the specified amount.
Example #9
We understand the above methods with the below sample java code:
Code:
package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.toString());
d = d.withSeconds(3000);
System.out.println(d.toString());
}
}
Output:
Conclusion
The Duration class is one of the built-in class in java, which is used to measure time in seconds and nanoseconds and add, subtract, and convert the duration, or, in simple words, the duration class allows performance operation on time or day duration. The duration class is available in java.time.Duration package of java.
Recommended Articles
This is a guide to Java Duration. Here we discuss the basic concept, syntax, top 50 lists of Java Duration, and different examples with proper codes and outputs. You can also go through our other related articles to learn more –