As a developer, you will inevitably encounter numerous scenarios in which you must compare two or more dates within a project. Whether you're sorting date values, validating user input, scheduling tasks, or analyzing data, proper date comparison is essential to ensuring that your application functions correctly and produces accurate results.
As you must be aware Java has two APIs for dealing with Dates,
- The legacy "java.util.Date" and "java.util.Calendar" classes from the util package.
- The "java.time" the new package introduced in Java 8.
Though the Date and Calendar classes from the util package should be avoided (issues such as being mutable, not being thread-safe - read more) we will cover them here just of completion.
1. Compare Dates using java.util.Date Class
a. Using compareTo(String date) method
Using this example you can compare two dates which are in String format.
Note that they have a valid date format (do add validation around it)
package org.code2care;
/**
*
* Java Program to compare two
* Dates using compareTo method
* from java.util.Date format.
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1 = "2023-03-01";
String date2 = "2023-03-05";
int dateCompareResult = date1.compareTo(date2);
if(dateCompareResult > 0) {
System.out.println("Date 1: " + date1 + " is after Date 2: " + date2);
} else if(dateCompareResult < 0) {
System.out.println("Date 1: " + date1 + " is before Date 2: " + date2);
} else {
System.out.println("Date 1: " + date1 + " is equal to Date 2: " + date2);
}
}
}
Output:
Date 1: 2023-03-01 is before Date 2: 2023-03-05
Here we have made use of the compareTo(String date) method from the java.util.Date format.
Based on the result of the compareTo() method which is an int value, you can write a condition to determine the relationship between the two dates.
- If the result is greater than 0, the first date is after the second date.
- If the result is less than 0, the first date is before the second date.
- If the result is 0, the two dates are equal.
b. Using the before(Date date) method
To make use of the before() method, the dates should be Date type from the java.util.date class.
Example:package org.code2care;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* Java Program to compare two
* Dates using before method
* from java.util.Date format.
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-04";
String date2Str = "2023-03-01";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = simpleDateFormat.parse(date1Str);
date2 = simpleDateFormat.parse(date2Str);
} catch (ParseException e) {
System.out.println("Invalid Date format");
e.printStackTrace();
}
if(date1.before(date2)) {
System.out.println("Date 1: " + date1Str + " is before Date 2: " + date2Str);
} else if(date2.before(date1)) {
System.out.println("Date 2: " + date2Str + " is before Date 1: " + date1Str);
} else {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
}
}
}
Output:
Date 2: 2023-03-01 is before Date 1: 2023-03-04
c. Using the after(Date date) method from java.util.Date class
-
Example:
package org.code2care;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* Java Program to compare two
* Dates using after method
* from java.util.Date format.
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-04";
String date2Str = "2023-03-01";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = simpleDateFormat.parse(date1Str);
date2 = simpleDateFormat.parse(date2Str);
} catch (ParseException e) {
System.out.println("Invalid Date format");
e.printStackTrace();
}
if(date1.after(date2)) {
System.out.println("Date 1: " + date1Str + " is after Date 2: " + date2Str);
} else if(date2.before(date1)) {
System.out.println("Date 2: " + date2Str + " is after Date 1: " + date1Str);
} else {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
}
}
}
Output:
Date 1: 2023-03-04 is after Date 2: 2023-03-01
d. Using the equals(Date date) method from java.util.date class
-
Example:
package org.code2care;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* Java Program to compare two
* Dates using equal method
* from java.util.Date format.
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-04";
String date2Str = "2023-03-01";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = simpleDateFormat.parse(date1Str);
date2 = simpleDateFormat.parse(date2Str);
} catch (ParseException e) {
System.out.println("Invalid Date format");
e.printStackTrace();
}
if(date1.equals(date2)) {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
} else {
System.out.println("Date 1: " + date1Str + " and Date 2: " + date2Str + " are not equal");
}
}
}
Output
Date 1: 2023-03-04 and Date 2: 2023-03-01 are not equal
e. Using all before, after, and equal methods together
-
Example:
package org.code2care;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* Java Program to compare two
* Dates using before, after
* and method equals methods
* from java.util.Date format.
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-01";
String date2Str = "2023-03-01";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = simpleDateFormat.parse(date1Str);
date2 = simpleDateFormat.parse(date2Str);
} catch (ParseException e) {
System.out.println("Invalid Date format");
e.printStackTrace();
}
if(date1.before(date2)) {
System.out.println("Date 1: " + date1Str + " is before Date 2: " + date2Str);
} else if(date1.after(date2)) {
System.out.println("Date 1: " + date1Str + " is after Date 2: " + date2Str);
} else if(date1.equals(date2)) {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
}
}
}
Output:
Date 1: 2023-03-01 is equal to Date 2: 2023-03-01
2. Compare dates using java.util.Calendar Class
a. Using the compareTo(Calendar cal) method
-
Example:
package org.code2care;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
*
* Java Program to compare two
* Dates using java.util.Calendar
* Class and compareTo method
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-03";
String date2Str = "2023-03-01";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
Date date1 = null;
Date date2 = null;
Calendar calDate1 = Calendar.getInstance();
Calendar calDate2 = Calendar.getInstance();
try {
date1 = simpleDateFormat.parse(date1Str);
date2 = simpleDateFormat.parse(date2Str);
calDate1.setTime(date1);
calDate2.setTime(date2);
} catch (ParseException e) {
System.out.println("Invalid Date format");
e.printStackTrace();
}
int compareResult = calDate1.compareTo(calDate2);
if(compareResult < 0) {
System.out.println("Date 1: " + date1Str + " is before Date 2: " + date2Str);
} else if(compareResult > 0) {
System.out.println("Date 1: " + date1Str + " is after Date 2: " + date2Str);
} else if(compareResult == 0) {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
}
}
}
Output: Date 1: 2023-03-03 is after Date 2: 2023-03-01
b. Using before, after, and equal methods
-
Example:
package org.code2care;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
*
* Java Program to compare two
* Dates using java.util.Calendar
* Class and compareTo method
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-01";
String date2Str = "2023-03-07";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
Date date1 = null;
Date date2 = null;
Calendar calDate1 = Calendar.getInstance();
Calendar calDate2 = Calendar.getInstance();
try {
date1 = simpleDateFormat.parse(date1Str);
date2 = simpleDateFormat.parse(date2Str);
calDate1.setTime(date1);
calDate2.setTime(date2);
} catch (ParseException e) {
System.out.println("Invalid Date format");
e.printStackTrace();
}
if(calDate1.before(calDate2)) {
System.out.println("Date 1: " + date1Str + " is before Date 2: " + date2Str);
} else if(calDate1.after(calDate2)) {
System.out.println("Date 1: " + date1Str + " is after Date 2: " + date2Str);
} else if(calDate1.equals(calDate2)) {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
}
}
}
Output: Date 1: 2023-03-01 is before Date 2: 2023-03-07
3. Using Java 8+ java.time package
It's recommended if you are using Java 8+, you should make use of LocalDate class. Note that this class is not timezone aware.
package org.code2care;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
*
* Java Program to compare two
* Local Dates using
* java.time.LocalDate isBefore,
* isAfter and isEqual methods
*
* @author code2care
*
*/
public class JavaDateCompare {
public static void main(String[] args) {
String date1Str = "2023-03-03";
String date2Str = "2023-03-07";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localdate1 = LocalDate.parse(date1Str, dateTimeFormatter);
LocalDate localdate2 = LocalDate.parse(date2Str, dateTimeFormatter);
if (localdate1.isBefore(localdate2)) {
System.out.println("Date 1: " + date1Str + " is before Date 2: " + date2Str);
} else if (localdate1.isAfter(localdate2)) {
System.out.println("Date 1: " + date1Str + " is after Date 2: " + date2Str);
} else if (localdate1.isEqual(localdate2)) {
System.out.println("Date 1: " + date1Str + " is equal to Date 2: " + date2Str);
}
}
}
Output: Date 1: 2023-03-03 is before Date 2: 2023-03-07
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- Detect swipes on Android Activity - Android
- How to create a New Project in Visual Studio Code (VS Code) - HowTos
- Change the default diff or commit editor for git - Git
- How to Get the Relative Path of a file in Python Program - Python
- Python: Convert Set to a List - Python
- How to stop or quit cat command? - HowTos
- Aw Snap! Something went wrong while displaying this webpage Error code: STATUS_INVALID_IMAGE_HASH - Chrome
- Change the default Line Encoding Notepad++ (CR LF) - NotepadPlusPlus