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(); } }
source share