Joe
Joe

Reputation: 141

Why does an invalid date parses successfully as a real date?

Can someone explain to me how to get the following method to return a value of false for the input shown? It's returning true, which is something I don't expect.

isDateValid("19/06/2012 5:00, 21:00","dd/MM/yyyy HH:mm")

I think this should return false, but apparently Java doesn't think so. The actual date string provided contains these extra characters at the end: ", 21:00".

public static boolean isDateValid(String date, String dateFormat) 
{
        try {
            DateFormat df = new SimpleDateFormat(dateFormat);
            df.setLenient(false);
            Date newDate = df.parse(date);
            System.out.println("Date value after checking for validity: " + newDate);
            return true;
        } catch (ParseException e) {
            return false;
        }
}

Upvotes: 5

Views: 84

Answers (1)

durron597
durron597

Reputation: 32323

parse doesn't necessarily use the entire String. This is very clear in the Javadoc, emphasis mine:

parse

public Date parse(String source) throws ParseException

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string. See the parse(String, ParsePosition) method for more information on date parsing.


You can detect if there are extra characters at the end of the string by using parse(String text, ParsePosition pos). If pos is not equal to the end of the String, then there were extra characters remaining at the end.

Here is a working program including test rig that will properly check this the way you intend. In this program, pos.getIndex() will be 0 if it can't parse at all, a number that is too small if there are extra characters at the end, and equal if it works the way you want

public class DateFormatTest {
  public static void main(String[] args) {
    // should be false
    System.out.println(isDateValid("19/06/2012 5:00, 21:00", "dd/MM/yyyy HH:mm"));
    System.out.println(isDateValid("19/06/201", "dd/MM/yyyy HH:mm"));
    
    System.out.println();
    
    // should be true
    System.out.println(isDateValid("19/06/2012 5:00", "dd/MM/yyyy HH:mm"));
  }

  public static boolean isDateValid(String date, String dateFormat) {
    ParsePosition pos = new ParsePosition(0);
    DateFormat df = new SimpleDateFormat(dateFormat);
    df.setLenient(false);
    df.parse(date, pos);

    return pos.getIndex() == date.length();
  }
}

Upvotes: 7

Related Questions