Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does non-lenient SimpleDateFormat parse dates with letters in?

When I run the following code I would expect a stacktrace, but instead it looks like it ignores the faulty part of my value, why does this happen?

package test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
  public static void main(final String[] args) {
    final String format = "dd-MM-yyyy";
    final String value = "07-02-201f";
    Date date = null;
    final SimpleDateFormat df = new SimpleDateFormat(format);
    try {
      df.setLenient(false);
      date = df.parse(value.toString());
    } catch (final ParseException e) {
      e.printStackTrace();
    }
    System.out.println(df.format(date));
  }

}

The output is:

07-02-0201

like image 397
Blem Avatar asked Feb 13 '13 10:02

Blem


People also ask

What is lenient in SimpleDateFormat?

The setLenient(boolean leniency) method in DateFormat class is used to specify whether the interpretation of the date and time of this DateFormat object is to be lenient or not.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

What can I use instead of SimpleDateFormat?

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

What is lenient parsing?

It is well explained in the doc: By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false) .


1 Answers

The documentation of DateFormat.parse (which is inherited by SimpleDateFormat) says:

The method may not use the entire text of the given string.
final String value = "07-02-201f";

In your case (201f) it was able to parse the valid string till 201, that's why its not giving you any errors.

The "Throws" section of the same method has defined as below:

ParseException - if the beginning of the specified string cannot be parsed

So if you try changing your string to

final String value = "07-02-f201";

you will get the parse exception, since the beginning of the specified string cannot be parsed.

like image 173
Jayamohan Avatar answered Oct 11 '22 20:10

Jayamohan