0

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;
}
Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114
  • Did you read the javadoc of [SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) (especially the part about the constructor that takes a format)? –  Mar 03 '16 at 12:30
  • Yes, is there a part for acceaptable dates? – Itsik Mauyhas Mar 03 '16 at 12:32
  • No you didn't or else you'd seen the "IllegalArgumentException - if the given pattern is invalid" part –  Mar 03 '16 at 12:33
  • missed that line. still it is only a part of mu question. – Itsik Mauyhas Mar 03 '16 at 12:35
  • Possible duplicate of [Check date with todays date](http://stackoverflow.com/questions/6537535/check-date-with-todays-date) –  Mar 03 '16 at 12:37

2 Answers2

2

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;
    }
}
Jesus Zavarce
  • 1,729
  • 1
  • 17
  • 27
  • 1
    You could `return DateUtils.isToday(date)` inside the `try`, and then drop the `return false` at the end. Simpler! (You could even inline the `date` variable) – janos Oct 30 '16 at 07:32
0
  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)