I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy". Example: java dateCheck 01/01/2014 15/03/2014 also i will need to check if a third date hardcoded into the program is before the second date.
To compare dates if a date is after another date, use the Calendar. after() method.
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.
Using CompareTo works as follows: Returns 0 if both dates are equal. Returns a value less than 0 if the date on which it is invoked is before the date passed in. Returns a value greater than 0 if the date on which it is invoked is after the date passed in.
try {
System.out.println("Enter first date : (dd/MM/yyyy)");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse(bufferRead.readLine());
System.out.println("Enter second date : (dd/MM/yyyy)");
Date date2 = sdf.parse(bufferRead.readLine());
System.out.println(date1 + "\n" + date2);
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
} else {
System.out.println("Date2 is after Date1");
}
} catch (IOException e) {
e.printStackTrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With