Duration compareTo() method in Java


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");

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements