Java .compareTo()
Published Jul 27, 2023
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: ADateobject to be compared chronologically with the given date.
It returns:
- The value
0ifargumentDateis equal tothisDate. - A value less than
0ifthisDateis beforeargumentDate. - A value greater than
0ifthisDateis 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)
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours