Why is an invalid date successfully parsed as a real date?

Can someone explain to me how to get the following method to return false for input? It returns true , which I do not expect.

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

I think this should return false , but, apparently, Java does not think so. The actual date string contains these extra characters at the end: ", 21:00" . ", 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; } } 
+5
source share
1 answer

parse does not necessarily use the entire String . This is very clear in Javadoc , my focus is:

parse

public Date parse(String source) throws ParseException

Parses text from the beginning of a given line to create a date. The method may not use all the text in a given string. For more information about parsing a date, see parse(String, ParsePosition) .


You can determine if there are additional characters at the end of a string using parse(String text, ParsePosition pos) . If pos not equal to the end of the line, then additional characters remain at the end.

Here is a working program that includes a test installation that will correctly verify this as you plan. In this program, pos.getIndex() will be 0 , if it cannot parse at all, a number that is too small if there are additional characters at the end, and it’s 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(); } } 
+7
source

All Articles