Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if one date is after another in java?

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.

like image 787
user3087192 Avatar asked Mar 15 '14 13:03

user3087192


People also ask

How do you check if a date is after another date in Java?

To compare dates if a date is after another date, use the Calendar. after() method.

How do you check if a date is greater than another date in Java?

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.

How do you check before and after dates?

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.


1 Answers

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();
}
like image 137
SUBZ Avatar answered Sep 19 '22 04:09

SUBZ