Thursday, August 28, 2025
HomeLanguagesJavaDuration compareTo(Duration) method in Java with Examples

Duration compareTo(Duration) method in Java with Examples

The compareTo(Duration) method of Duration Class in java.time package is used to compare this duration with the duration passed as the parameter.

Syntax:

public int compareTo(Duration otherDuration)

Parameters: This method accepts a parameter otherDuration which is the duration to which this duration will be compared to.

Return Value: This method returns an int value where negative value means that otherDuration is larger than this value, zero means otherDuration is equal to this duration, and positive value means this duration is larger than the otherDuration.

Below examples illustrate the Duration.compareTo() method:

Example 1:




// Java code to illustrate compareTo() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration using parse() method
        Duration duration1
            = Duration.parse("P2DT3H4M");
  
        // Duration using ofDays() method
        Duration duration2
            = Duration.ofDays(10);
  
        // Compare the durations
        // using compareTo() method
        System.out.println(duration1
                               .compareTo(duration2));
    }
}


Output:

-1

Example 2:




// Java code to illustrate compareTo() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration using ofHours() method
        Duration duration1
            = Duration.ofHours(5);
  
        // Duration using ofHours() method
        Duration duration2
            = Duration.ofHours(5);
  
        // Compare the durations
        // using compareTo() method
        System.out.println(duration1
                               .compareTo(duration2));
    }
}


Output:

0

Example 3:




// Java code to illustrate compareTo() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration using ofDays() method
        Duration duration1
            = Duration.ofDays(5);
  
        // Duration using ofHours() method
        Duration duration2
            = Duration.ofHours(5);
  
        // Compare the durations
        // using compareTo() method
        System.out.println(duration1
                               .compareTo(duration2));
    }
}


Output:

1

Reference: Oracle Doc

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32244 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11787 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11832 POSTS0 COMMENTS
Shaida Kate Naidoo
6728 POSTS0 COMMENTS
Ted Musemwa
7009 POSTS0 COMMENTS
Thapelo Manthata
6684 POSTS0 COMMENTS
Umr Jansen
6697 POSTS0 COMMENTS