
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
Have Questions? Post them here!
- How to Get List of All Country Codes in Java Using Locale Class
- Unsupported major.minor version 52.0 in java
- Java - How to set custom thread name?
- Get the current timestamp in Java
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- [fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring
- java: unclosed string literal [Error]
- Convert Java Byte Array to String with code examples
- Error: Can not find the tag library descriptor for
- Java 8 - Convert List to Map Examples
- Java - Calculate time taken for the code to execute in milliseconds or nanoseconds
- Fix java.net.ProtocolException: Invalid HTTP method
- Java: Convert Stream to List
- Java equals method - Tutorial
- List of Java JDBC Database Driver Jars, Classes and URLs Details
- Read YAML file Java Jackson Library
- How to display Java Date Time timezone GMT/UTC offset using SimpleDateFormat
- List of Java Keywords
- Enable JSON Pretty Print in Java Jackson
- How to Word-Warp Console logs in IntelliJ
- Convert Map to List in Java 8 using Stream API
- Create a Directory using Java Code
- Ways to Convert Integer or int to Long in Java
- [Program] How to read three different values using Scanner in Java
- Java JDBC Example with Oracle Database Driver Connection
- Check help on commands while being on sftp> prompt - FTP
- How to install npm on Ubuntu - Linux
- How to install Zoom Add-in to Outlook (Mac) - MacOS
- How to update SharePoint List Item programmatically using C#.Net - SharePoint
- Set Python 3.8 as a default python version on macOS - MacOS
- Setting $JAVA_HOME Environment Variable in macOS - MacOS
- JSON Schema Validator Libraries: JSON Tutorial - Json-Tutorial
- Top 3 Awesome Text Editors developers prefer at workplace - Sublime