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
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.
Example: Java Compare two dates Using Date. We can use compareTo() function from Date class to compare the two dates. compareTo() function returns: 0 if both dates are equal. 1 if date1 comes after date2.
You can't compare just any date string. For instance, "13-Dec-2020" < "20-Apr-2020" alphabetically but not conceptually. But ISO date strings are neatly comparable, for instance, "2020-12-13" > "2020-04-20" both conceptually and alphabetically.
In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement. We can declare variables easily by using the keyword DECLARE before the variable name.
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() ));
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