Here is an example:
public MyDate() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/d");
sdf.setLenient(false);
String t1 = "2011/12/12aaa";
System.out.println(sdf.parse(t1));
}
2011/12/12aaa is not a valid date string. However the function prints "Mon Dec 12 00:00:00 PST 2011" and ParseException isn't thrown.
Can anyone tell me how to let SimpleDateFormat treat "2011/12/12aaa" as an invalid date string and throw an exception?
The formats are case-sensitive. Use yyyy for year, dd for day of month and MM for month. You need to read the javadoc of SimpleDateFormat more carefully, Take special care for lower-case and upper-case in the patterns.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.
2.2.Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. So SimpleDateFormat instances are not thread-safe, and we should use them carefully in concurrent environments.
Java 8 LocalDate may be used:
public static boolean isDate(String date) {
try {
LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
return true;
} catch (DateTimeParseException e) {
return false;
}
}
If input argument is "2011/12/12aaaaaaaaa"
, output is false
;
If input argument is "2011/12/12"
, output is true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With