- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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!
Advertisements