Search code examples
javadatecalendarsimpledateformat

Comparing user input date with current date


Hi im trying to compare a user inputted date (as a string) with the current date so as to find out if the date is earlier or older.

My current code is

String date;
Date newDate;
Date todayDate, myDate;     
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");

while(true)
{
    Scanner s = new Scanner (System.in);
    date = s.nextLine();
    Calendar cal = Calendar.getInstance();
    try {
        // trying to parse current date here
        // newDate = dateFormatter.parse(cal.getTime().toString()); //throws exception

        // trying to parse inputted date here
        myDate = dateFormatter.parse(date); //no exception
    } catch (ParseException e) {
        e.printStackTrace(System.out);
    }

}

Im trying to get both user input date and current date into two Date objects, so that i can use Date.compareTo() to simplify comparing dates.

I was able to parse the user input string into the Date object. However the current date cal.getTime().toString() does not parse into the Date object due to being an invalid string.

How to go about doing this? Thanks in advance


Solution

  • You can get the current Date with:

    todayDate = new Date();
    

    EDIT: Since you need to compare the dates without considering the time component, I recommend that you see this: How to compare two Dates without the time portion?

    Despite the 'poor form' of the one answer, I actually quite like it:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    sdf.format(date1).equals(sdf.format(date2));
    

    In your case, you already have:

    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");
    

    so I would consider (for simplicity rather than performance):

    todayDate = dateFormatter.parse(dateFormatter.format(new Date() ));