Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?

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?

like image 678
Terminal User Avatar asked Dec 08 '11 08:12

Terminal User


People also ask

Is SimpleDateFormat case sensitive?

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.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What does SimpleDateFormat parse do?

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.

Why is SimpleDateFormat not thread-safe?

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.


1 Answers

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

like image 65
David Avatar answered Oct 02 '22 13:10

David