Why java SimpleDateFormat can parse formatted text with extra characters?

simpledateformat java example
simpledateformat java 8
simpledateformat parse
how to convert string to a particular date format in java
convert date format from yyyy-mm-dd to mm/dd/yyyy in java
how to convert string to date in java in yyyy-mm-dd format
string.format date java
simpledateformat parse example

I am parsing date strings from user input with MM-dd-yyyy HH:mm:ss format, and I found 12-20-2012 10:10:10 abcdexxxx could be pasred as well. How can this happen? Here is my code:

SimpleDateFormat df = new SimpleDateFormat( "MM-dd-yyyy HH:mm:ss" );
String currColValue = "12-20-2012 10:10:10 abcdexxxx";
try{
    d=df.parse( currColValue );
}catch( ParseException e ){
    System.out.println("Error parsing date: "+e.getMessage());
}

But there is no exception, the String value is parsed to be a Date. Why?

Per the Javadoc of the parse method:

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.

(emphases mine).

Contrary to the implication of comments above, this has nothing to do with lenient parsing; rather, it's just that this method is not intended to consume the whole string. If you wish to validate that it consumed the whole string, I suppose you could set up a ParsePosition object and use the two-arg overload, and then examine the ParsePosition afterward to see if it parsed to the end of the string.

The Java SimpleDateFormat class can parse and format dates according to custom When parsing dates, the Java SimpleDateFormat typically parses the date from a Java String. Characters other than these will be treated as normal text to insert into the Here are the methods you can use to set additional symbols: I am parsing date strings from user input with MM-dd-yyyy HH:mm:ss format, and I found 12-20-2012 10:10:10 abcdexxxx could be pasred as well. How can this happen?

Check SimpleDateFormat.parse(String) doc. It clearly says it.

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.

http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#parse(java.lang.String)

I have covered SimpleDateFormat in more detail in my Java Internationalization tutorial, It is also possible to parse and format dates using the newer Java to parse and format dates from and to the newer date time classes added in Java 8. Below is a list of the most common pattern letters you can use. java.text.SimpleDateFormat. All Implemented Interfaces: Serializable, Cloneable. public class SimpleDateFormatextends DateFormat. SimpleDateFormatis a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.

java.time

I should like to contribute the modern answer. This question was asked just the month before java.time, the modern Java date and time API, came out, which we all should be using now.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss");
    String currColValue = "12-20-2012 10:10:10 abcdexxxx";
    try {
        LocalDateTime ldt = LocalDateTime.parse(currColValue, formatter);
        // Do something with ldt
    } catch (DateTimeParseException e) {
        System.out.println("Error parsing date and time: " + e.getMessage());
    }

Output:

Error parsing date and time: Text '12-20-2012 10:10:10 abcdexxxx' could not be parsed, unparsed text found at index 19

Contrary to the old SimpleDateFormat class the parse methods of the modern classes do insist on parsing the entire string (there is a way to parse only part of the string if that is what you require). Also please note the precision and clarity of the exception message. By the way, SimpleDateFormat is not only long outdated, it is also notoriously troublesome. You found just one of many surprising problems it has. I recommend that you no longer use SimpleDateFormat and Date.

Link: Oracle tutorial: Date Time explaining how to use java.time.

SimpleDateFormat is a concrete class for formatting and parsing dates Text: For formatting, if the number of pattern letters is 4 or more, the full  java.text.SimpleDateFormat. SimpleDateFormatis a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormatallows you to start by choosing any user-defined patterns for date-time formatting.

I want to contibute to the above correct answers with examples, using the method overload

public Date parse(String text, ParsePosition pos);

To parse the exact whole string just create a new ParsePosition object (with index 0, indicating that parse needs to start from begin), pass it to the method, and inspect its index property after parse. Index is where the parse did end. If matches with string length then the string matches exactly form start to end.

Here is a unit test demonstrating it

public class DateParseUnitTest {

    @Test
    public void testParse(){
        Date goodDate = parseExact("2019-11-05");
        Date badDate1 = parseExact("foo 2019-11-05");
        Date badDate2 = parseExact("2019-11-05 foo");

        assert(goodDate != null);
        assert(badDate1 == null);
        assert(badDate2 == null);
    }

    @Nullable
    private Date parseExact(@NonNull String text){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        ParsePosition pos = new ParsePosition(0);
        Date date = formatter.parse(text, pos);
        if (pos.getIndex() != text.length())
            return null;

        return date;
    }
}

We can easily parse and format dates in Java with the directives that SimpleDateFormat does (though requiring some extra characters). Parsing is conversion of String into a java.util.Date instance. We can parse a string to a date instance using parse () method of the SimpleDateFormat class. For parsing a String to Date we need an instance of the SimpleDateFormat class and a string pattern as input for the constructor of the class.

NET's built-in classes you want the custom date and time format strings This is the case with SimpleDateFormat in Java and with DateTime. The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local). Using the methods of this class you can parse String to Date or, format Date to String. Formatting Date to String. You can format a given String to Date object using the parse() method of the SimpleDateFormat class

Converting strings to desired date format is a time consuming and tedious a custom format defined by special formatting characters where as the java.text. In this example, SimpleDateFormat:class is used to format date into text and parse text into date how to parse xml in j2me tutorial how to parse xml in j2me tutorial i want to parse xml file in j2me wireless toolkit.i saw ur examples & source code for parsing xml file in j2me & i try to execute same example on my pc i some how manage to run

Added in API level 1 java.text.Format. ↳, java.text.DateFormat. ↳, java.text.​SimpleDateFormat. SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is  Date Parsing and Formatting with DateFormat: 2.41.2. Parsing the Time Using a Custom Format: 2.41.3. Parse with a custom format: 2.41.4. Parse with a default format: 2.41.5. Parse string date value input with SimpleDateFormat('dd-MMM-yy') 2.41.6. Parse a date and time: 2.41.7. Parse string date value input with SimpleDateFormat('E, dd MMM yyyy

Comments
  • Did you look at setLenient?
  • yes. I set it to be false and still parsed.
  • possible duplicate of What is the use of "lenient "?
  • Yes. Now we are using JDK 1.8 and I prefer to using LocalDate/LocalDateTime/DateTimeFormatter... but I could not use this version after it just released.