Table of contents
1.
Introduction
2.
Fields present in Class
3.
Methods present in class
4.
Example
4.1.
Java
5.
Frequently Asked Questions
5.1.
Can I use negative values when creating durations with the ofXXX() methods?
5.2.
How can I convert a Duration to a different time unit, such as hours or minutes? 
5.3.
Is it possible to compare two Duration instances? 
6.
Conclusion
Last Updated: Jul 22, 2024
Easy

Java Time Duration

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java is a popular programming language used for building various applications. One important aspect of Java is handling time durations. The Java Time Duration class allows us to work with amounts of time, such as seconds, minutes, hours, & days. It provides a convenient way to perform calculations & comparisons on durations. 

Java Time Duration

In this article, we will discuss the Java Time Duration class, its fields, and methods, and examples of how to use it effectively.

Fields present in Class

The Java Time Duration class contains several fields that represent different time units. These fields are constants that can be used to create & compare durations. Here are the main fields available in the Duration class:

1. ZERO: Represents a duration of zero.
 

2. NANOS_PER_SECOND: The number of nanoseconds in one second (1,000,000,000).
 

3. NANOS_PER_MILLI: The number of nanoseconds in one millisecond (1,000,000).
 

4. NANOS_PER_MICRO: The number of nanoseconds in one microsecond (1,000).
 

5. SECONDS_PER_DAY: The number of seconds in one day (86,400).
 

6. SECONDS_PER_HOUR: The number of seconds in one hour (3,600).
 

7. SECONDS_PER_MINUTE: The number of seconds in one minute (60).


These fields are useful when working with durations & performing calculations. For example, you can use SECONDS_PER_DAY to convert a duration from days to seconds.

Duration threeDays = Duration.ofDays(3);
long seconds = threeDays.getSeconds(); // Returns 259,200 (3 * 86,400)


The fields provide a convenient way to express durations in different units & perform conversions between them.

Methods present in class

The Java Time Duration class provides various methods to create, manipulate, & compare durations. Here are some commonly used methods:

1. ofDays(long days): Creates a Duration representing the specified number of days.
 

2. ofHours(long hours): Creates a Duration representing the specified number of hours.
 

3. ofMinutes(long minutes): Creates a Duration representing the specified number of minutes.
 

4. ofSeconds(long seconds): Creates a Duration representing the specified number of seconds.
 

5. ofMillis(long millis): Creates a Duration representing the specified number of milliseconds.
 

6. ofNanos(long nanos): Creates a Duration representing the specified number of nanoseconds.
 

7. between(Temporal startInclusive, Temporal endExclusive): Obtains a Duration between two temporal objects.
 

8. from(TemporalAmount amount): Obtains a Duration from another TemporalAmount.
 

9. get(TemporalUnit unit): Gets the value of the requested unit from this duration.
 

10. isZero(): Checks if this duration is zero length.
 

11. isNegative(): Checks if this duration is negative.
 

12. plus(Duration duration): Returns a copy of this duration with the specified duration added.
 

13. minus(Duration duration): Returns a copy of this duration with the specified duration subtracted.
 

14. multipliedBy(long multiplicand): Returns a new duration with this duration multiplied by the specified value.
 

15. dividedBy(long divisor): Returns a new duration with this duration divided by the specified value.


These methods allow you to create durations using different units, perform operations like addition & subtraction, check properties of durations, & convert between durations & other temporal amounts.

For example, to create a duration of 2 hours & 30 minutes, you can use the following code:

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


This creates a Duration object representing 2 hours & 30 minutes by combining the ofHours() & plusMinutes() methods.

Example

Let's take a look at a proper example that shows the usage of the Java Time Duration class:

  • Java

Java

import java.time.Duration;

import java.time.LocalTime;

public class DurationExample {

   public static void main(String[] args) {

       // Creating durations

       Duration twoHours = Duration.ofHours(2);

       Duration thirtyMinutes = Duration.ofMinutes(30);

       Duration tenSeconds = Duration.ofSeconds(10);

       // Combining durations

       Duration totalDuration = twoHours.plus(thirtyMinutes).plus(tenSeconds);

       System.out.println("Total Duration: " + totalDuration);

       // Calculating duration between two LocalTime instances

       LocalTime startTime = LocalTime.of(9, 0);

       LocalTime endTime = LocalTime.of(11, 30);

       Duration difference = Duration.between(startTime, endTime);

       System.out.println("Duration between startTime & endTime: " + difference);

       // Accessing duration values

       long seconds = totalDuration.getSeconds();

       long nanoseconds = totalDuration.toNanos();

       System.out.println("Total seconds: " + seconds);

       System.out.println("Total nanoseconds: " + nanoseconds);

       // Comparing durations

       boolean isEqual = twoHours.equals(Duration.ofMinutes(120));

       boolean isNegative = tenSeconds.isNegative();

       System.out.println("twoHours equals 120 minutes? " + isEqual);

       System.out.println("tenSeconds is negative? " + isNegative);

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

Total Duration: PT2H30M10S
Duration between startTime & endTime: PT2H30M
Total seconds: 9010
Total nanoseconds: 9010000000000
twoHours equals 120 minutes? true
tenSeconds is negative? false


In this example, we create durations using the `ofHours()`, `ofMinutes()`, & `ofSeconds()` methods. We then combine these durations using the `plus()` method to get the total duration.

We also demonstrate calculating the duration between two `LocalTime` instances using the `Duration.between()` method.

The example shows how to access duration values in seconds & nanoseconds using the `getSeconds()` & `toNanos()` methods, respectively.

Finally, we compare durations using the `equals()` method & check if a duration is negative using the `isNegative()` method.

Frequently Asked Questions

Can I use negative values when creating durations with the ofXXX() methods?

Yes, you can pass negative values to the ofXXX() methods to create negative durations.

How can I convert a Duration to a different time unit, such as hours or minutes? 

You can use the toXXX() methods, like toHours() or toMinutes(), to convert a Duration to a different time unit.

Is it possible to compare two Duration instances? 

Yes, you can use the compareTo() method to compare two Duration instances. It returns a negative value, zero, or a positive value if the first duration is less than, equal to, or greater than the second duration, respectively.

Conclusion

In this article, we have learned about the Java Time Duration class & how it helps us work with time durations in Java. We discussed about the fields available in the Duration class, such as ZERO & SECONDS_PER_DAY, which provide convenient constants for common time units. We also looked at the various methods provided by the Duration class, including ofXXX() methods for creating durations, plus() & minus() for arithmetic operations, & methods for comparing & converting durations.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass