Categories
date java

compare two dates in java example

 

In this post, we will learn to compare two dates in java example

There are multiple ways to compare two dates in java.

In the First example we will learn to compare dates using compareTo() method

While using compareTo() method we are having 3 chances of output. Below are the possible output

0 – When both the dates are equal

1 – When date 1 is greater than date 2

-1 – When date 1 is lesser than date 2

Syntax
date1.compareTo(date2)
Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample {
	public static void main(String[] args) {
		try {

			String date1 = "22/02/2020";
			String date2 = "21/02/2020";
			DateFormat format = new SimpleDateFormat("DD/MM/yyyy");
			Date dateObj1 = format.parse(date1);
			Date dateObj2 = format.parse(date2);

			// If Both the date are same comparTo Method will return 0
			if (dateObj1.compareTo(dateObj2) == 0) {
				System.out.println("Both the dates are Equal !!");
			} // If date1 greater than date 2 it will return 1
			else if (dateObj1.compareTo(dateObj2) > 0) {

				System.out.println("Date 1 is greater than date 2");
			} // If date1 lesser than date 2 it will return -1
			else {
				System.out.println("Date 1 is lesser than date 2");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Date 1 is greater than date 2

Using equals(),after(),before()

In the above example, we learned using compareTo() method. But we can compare dates using predefined functions also.

Below example is another way to compare two dates in java 

equals() – return true if both the dates are equal

after() – return true if date 1 greater than date 2

before() – return true if date 1 lesser than date 2

Example

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateCompareExample {
	public static void main(String[] args) {
		try {

			String date1 = "20/02/2020";
			String date2 = "21/02/2020";
			DateFormat format = new SimpleDateFormat("DD/MM/yyyy");
			Date dateObj1 = format.parse(date1);
			Date dateObj2 = format.parse(date2);

			// If Both the date are same comparTo Method will return 0
			if (dateObj1.equals(dateObj2)) {
				System.out.println("Both the dates are Equal !!");
			} // If date1 greater than date 2 it will return 1
			else if (dateObj1.after(dateObj2)) {

				System.out.println("Date 1 is after than date 2");
			} // If date1 lesser than date 2 it will return -1
			else if (dateObj1.before(dateObj2)) {
				System.out.println("Date 1 is before than date 2");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
Date 1 is before than date 2
Reference

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#compareTo-java.util.Date-

Related Articles

convert String to date in java with example

Leave a Reply

Your email address will not be published. Required fields are marked *