

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to compare two dates in Java?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
Syntax
int compareTo(T o)
Example
import java.text.*; import java.util.Date; public class CompareTwoDatesTest { public static void main(String[] args) throws ParseException { SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = sdformat.parse("2019-04-15"); Date d2 = sdformat.parse("2019-08-10"); System.out.println("The date 1 is: " + sdformat.format(d1)); System.out.println("The date 2 is: " + sdformat.format(d2)); if(d1.compareTo(d2) > 0) { System.out.println("Date 1 occurs after Date 2"); } else if(d1.compareTo(d2) < 0) { System.out.println("Date 1 occurs before Date 2"); } else if(d1.compareTo(d2) == 0) { System.out.println("Both dates are equal"); } } }
In the above example, the date d1 occurs before the date d2, so it can display "Date 1 occurs before Date 2" in the console.
Output
The date 1 is: 2019-04-15 The date 2 is: 2019-08-10 Date 1 occurs before Date 2
- Related Questions & Answers
- How to compare two Dates in C#?
- How to compare two dates in String format in Java?
- How to compare two dates along with time in Java?
- How to compare two dates with JavaScript?
- PHP program to compare two dates
- Compare Dates in Java
- How to compare dates in JavaScript?
- How to Compare two String in Java?
- How to compare two arrays in Java?
- What are various ways to compare dates in Java?
- How do we compare Python Dates?
- How to count days between two dates in Java
- Compare two Strings in Java
- Java Program to Compare Two Strings
- Java Program to compare two sets
Advertisements