# Duration compareTo() method in Java

Java 8Object Oriented ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

Two durations can be compared using the compareTo() method in the Duration class in Java. This method requires a single parameter i.e. the duration to be compared.

If the first duration is greater than the second duration it returns a positive number, if the first duration is lesser than the second duration it returns a negative number and if both the durations are equal it returns zero.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.time.Duration;
public class Demo {
public static void main(String[] args) {
Duration d1 = Duration.ofHours(8);
Duration d2 = Duration.ofHours(6);
System.out.println("The first duration is: " + d1);
System.out.println("The second duration is: " + d2);
int val = d1.compareTo(d2);
if(val > 0)
System.out.println("The first duration is greater than the second duration");
else if(val < 0)
System.out.println("The first duration is lesser than the second duration");
else
System.out.println("The durations are equal");
}
}

## Output

The first duration is: PT8H
The second duration is: PT6H
The first duration is greater than the second duration

Now let us understand the above program.

First the two durations are displayed. Then the durations are compared using the compareTo() method and the result is displayed using if else statement. A code snippet that demonstrates this is as follows −

Duration d1 = Duration.ofHours(8);
Duration d2 = Duration.ofHours(6);
System.out.println("The first duration is: " + d1);
System.out.println("The second duration is: " + d2);
int val = d1.compareTo(d2);
if(val > 0)
System.out.println("The first duration is greater than the second duration");
else if(val < 0)
System.out.println("The first duration is lesser than the second duration");
else
System.out.println("The durations are equal");
Updated on 30-Jul-2019 22:30:25