1

User should enter date in the next format yyyy-MM-dd. So I check it on my side using:

public static boolean isDateValid(SimpleDateFormat dateFormat, String date) {
    try {
        dateFormat.parse(date);
        return true;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }
}

But it returns true even I enter 12-12-2012 for the

SimpleDateFormat("yyyy-MM-dd")
pvllnspk
  • 5,667
  • 12
  • 59
  • 97
  • why do you want to force the user doing this - shouln't it be enough for you to just check if its a valid date - no matter what format? --> http://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java after oyu have validated you can you your simpledateformat to format the date the way you want it to be – OschtärEi Dec 04 '12 at 15:38
  • @tenhouse : in this case, what date would 10-12-2012 be ? 10th of december or 12th of october ? – njzk2 Dec 04 '12 at 15:41
  • @njzk2 agreed. I didn't think of that – OschtärEi Dec 04 '12 at 15:54
  • is this date string came from user input like EditText? ... if so ... you can use DatePicker or DatePickerDialog instead – Selvin Dec 04 '12 at 15:54
  • @tenhouse : but the opposite is true as well : if this is user input, the user may type 2012-12-10 as wel as 10-12. – njzk2 Dec 04 '12 at 16:32

1 Answers1

2

You can use DateFormat.setLenient(false), to avoid doing lenient parsing: -

    try {
        dateFormat.setLenient(false);
        dateFormat.parse(date);
        return true;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    }

From the docs: -

With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525