

- 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
Java Program to Match Dates
Firstly, we have considered the following two dates.
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = s.parse("2018-10-15"); Date d2 = s.parse("2018-11-10");
Now, use the compareTo() method to compare both the dates. The results are displayed on the basis of the return value.
if (d1.compareTo(d2) > 0) { System.out.println("Date1 is after Date2!"); } else if (d1.compareTo(d2) < 0) { System.out.println("Date1 is before Date2!"); } else if (d1.compareTo(d2) == 0) { System.out.println("Date1 is equal to Date2!"); } else { System.out.println("How to get here?"); }
Example
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] args) throws ParseException { SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = s.parse("2018-10-15"); Date d2 = s.parse("2018-11-10"); if (d1.compareTo(d2) > 0) { System.out.println("Date1 is after Date2!"); } else if (d1.compareTo(d2) < 0) { System.out.println("Date1 is before Date2!"); } else if (d1.compareTo(d2) == 0) { System.out.println("Date1 is equal to Date2!"); } else { System.out.println("How to get here?"); } } }
Output
Date1 is before Date2!
- Related Questions & Answers
- Java Program to Match Zip Codes
- Java Program to get milliseconds between dates
- Java Program to set a spinner of dates in Java
- Java Program to check if two dates are equal
- PHP program to compare two dates
- Java Program to Display Dates of Calendar Year in Different Format
- Compare Dates in Java
- Java regex program to match parenthesis "(" or, ")".
- Java Program to compare dates if a date is after another date
- Java Program to compare dates if a date is before another date
- How to compare two dates in Java?
- Finding a Match Within Another Match Java regular expressions
- Program to match vowels in a string using regular expression in Java
- Use Pattern class to match in Java
- C# Program to get the difference between two dates
Advertisements