Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

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 SimpleDateFormat and the next step if the dateInString 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;
}

Upvotes: 0

Views: 671

Answers (2)

Jesus Zavarce
Jesus Zavarce

Reputation: 1759

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;
    }
}

Upvotes: 2

Benjamin Gaunitz
Benjamin Gaunitz

Reputation: 71

  1. For checking the format you could do something like this:

    SimpleDateFormat dateFormat;
    
    try {
        dateFormat = new SimpleDateFormat(format);
    }
    catch(IllegalArgumentException e){
        //handle wrong format
    }
    
  2. Check if date is today

    dateInString.equals(dateFormat.format(new Date()))
    
  3. Have a look at Joda Time Library which is much more convenient ;)

PS: Have not tested the, but thats roughly the way to go.

A cleaner way would be to split the method up e.g.

  • boolean isDateFormatValid(String format)
  • boolean isDateToday(String dateInString, String format)

Upvotes: 0

Related Questions