[java] How to check if a date is greater than another in Java?

I am working on a Java application which generates a report for a duration entered by a user in the command line. The user needs to enter the dates in the following format: dd-MM-yyyy

> java report startDate endDate

Example:

java report 01-01-2013 31-03-2013

In the code I save the dates in two strings. I have to make sure that the start date entered by the user should be a date earlier than the end-date. Is there an built-in function which can help me achieve this by passing these two strings to it?

This question is related to java date

The answer is


Parse the string into date, then compare using compareTo, before or after

Date d = new Date();
d.compareTo(anotherDate)

i.e

Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(date1string)
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(date2string)

date1.compareTo(date2);

Copying the comment provided below by @MuhammadSaqib to complete this answer.

Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument, and a value greater than 0 if this Date is after the Date argument. and NullPointerException - if anotherDate is null.

javadoc for compareTo http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)


You need to use a SimpleDateFormat (dd-MM-yyyy will be the format) to parse the 2 input strings to Date objects and then use the Date#before(otherDate) (or) Date#after(otherDate) to compare them.

Try to implement the code yourself.


Parse the two dates firstDate and secondDate using SimpleDateFormat.

firstDate.after(secondDate);

firstDate.before(secondDate);