SimpleDateFormat Request

I have the following snippet

Date date=null;
    SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
    try {
        date= sdf.parse("2001-02-2012");
        System.out.println(date);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }

      

It's weird that it doesn't throw a syntax exception, does it?

+3


source to share


3 answers


The problem is your input is unexpected. SimpleDateFormat then tries to interpret it in a useful way anyway. So, in your case, there are 2001

days that just convert to weeks, months, and years. Your date Mon Jul 24 00:00:00 GMT 2017

. You can check it out on ideone: http://ideone.com/bfgogz



To "fix" it, you can add sdf.setLenient(false);

to accept only the data that you have specified in this way.

+3


source


Acc. to documents:

public Date parse(String source) throws ParseException

      

Parses the text from the beginning of the given string to create a date. The method may not use all the text of the given line .



and

throws ParseException

- if the beginning of the specified line cannot be parsed.

See: DateFormat

+2


source


It will throw ParseException

if you analyze it unevenly. DateFormat#setLenient(false)

he also knows strict parsing .

Specify whether to mitigate date and time parsing. With soft parsing, the parser can use heuristics to interpret inputs that do not exactly match this object. With strict parsing, Inputs must match this object.

Documentation -

SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
sdf.setLenient(false);
try{
    date = sdf.parse("2001-02-2012");
    System.out.println(date);
} catch (ParseException ex) {
    ex.printStackTrace();
}

      

Result -

java.text.ParseException: Unparseable date: "2001-02-2012"

      

Note. The default is to Dateformat/SimpleDateFormat

handle it forgiving.

+2


source







All Articles