
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Compare Dates in Java to Check If One Date Is Before Another
To compare dates if a date is before another date, use the Calendar.before() method.
The Calendar.before() method returns whether this Calendar's time is before the time represented by the specified Object. First, let us set a date which is before the current date
Calendar date1 = Calendar.getInstance(); date1.set(Calendar.YEAR, 2010); date1.set(Calendar.MONTH, 11); date1.set(Calendar.DATE, 20);
Here is our current date
Calendar date = Calendar.getInstance();
Now, use the after() method to compare both the dates as shown in the following example
The following is an example
Example
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar date1 = Calendar.getInstance(); date1.set(Calendar.YEAR, 2010); date1.set(Calendar.MONTH, 11); date1.set(Calendar.DATE, 20); java.util.Date dt = date1.getTime(); System.out.println("Date One = "+dt); Calendar date2 = Calendar.getInstance(); System.out.println("Date Two = " + (date2.get(Calendar.MONTH) + 1) + "-" + date2.get(Calendar.DATE) + "-" + date2.get(Calendar.YEAR)); if(date1.before(date2)) { System.out.println("Date One is before Date Two!"); } else { System.out.println("Date One is after Date Two!"); } } }
Output
Date One = Mon Dec 20 06:48:11 UTC 2010 Date Two = 11-23-2018 Date One is before Date Two!
Advertisements