.compareTo()
Published Jul 27, 2023
Contribute to Docs
The Date.compareTo()
method compares one Date
object with another and returns an integer value accordingly.
Syntax
thisDate.compareTo(argumentDate)
The Date.compareTo()
takes only one parameter:
argumentDate
: ADate
object to be compared chronologically with the given date.
It returns:
- The value
0
ifargumentDate
is equal tothisDate
. - A value less than
0
ifthisDate
is beforeargumentDate
. - A value greater than
0
ifthisDate
is afterargumentDate
.
The function throws a single exception, a NullPointerException, if argumentDate
is null.
Example
The following example shows the implementation of Date.compareTo()
:
import java.util.Date;public class Main {public static void main(String[] args) {Date firstDate = new Date(2023, 1, 18);Date secondDate = new Date(2023, 1, 19);Date thirdDate = new Date(2023, 1, 18);Date fourthDate = new Date(2023, 1, 17);Date nullDate = null;System.out.println("Comparing firstDate and secondDate: " + firstDate.compareTo(secondDate));System.out.println("Comparing firstDate and thirdDate: " + firstDate.compareTo(thirdDate));System.out.println("Comparing firstDate and fourthDate: " + firstDate.compareTo(fourthDate));System.out.println("Comparing firstDate and nullDate: " + firstDate.compareTo(nullDate));}}
The output will be:
Comparing firstDate and secondDate: -1Comparing firstDate and thirdDate: 0Comparing firstDate and fourthDate: 1Exception in thread "main" java.lang.NullPointerExceptionat java.base/java.util.Date.getMillisOf(Date.java:956)at java.base/java.util.Date.compareTo(Date.java:979)at Main.main(Main.java:15)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours