Itsik Mauyhas Itsik Mauyhas - 1 year ago 93
Java Question

Java - check if date format is acceptable and compare dates based on it

I want to create a simple function that gets 2 params - date format(dd/mm/yyyy, dd-mm-yyyy etc...) and a string that in this format(1/4/2015, 1-4-2015).
First of all is there a way to check if the format is acceptable by

and the next step if the
is today, here is my code:

public boolean checkDate(String dateInString, String format){
boolean result = false;
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
//parse the string to date
Date inputDate = dateFormat.parse(dateInString);
//check if the date is today using the format
//if the date is today then
result = true;

return result;

Answer Source

You could use this Utility class (DateUtils) with this implementation:

public boolean checkDate(String dateInString, String format){
    try {
        return DateUtils.isToday(new SimpleDateFormat(format).parse(dateInString)); 
    } catch (ParseException e) {
        return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download