Weird behavior in java.text.SimpleDateFormat?

Extract from JavaDoc for setLenient: public void setLenient(boolean lenient) Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

If you set it to false, you will get ParseException.

If you use the DateFormat.parse() function, the string must satisfy the input format. If it doesn't do it, the parse funtion parse wrong. Here a comment abou this in the javaDoc: 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). Then, your problem would be fixed adding the setLenient(false) line. In this case, Java throws the exception.

Regards!

Well, the input would be split into 3 components: year, month, day and you'd get month = -12 and day = -21 (for correction see below). Try to parse 2012/12/21 and you'll get the exception :) Edit: excerpt from the JavaDoc: Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number. Edit2: Correction Looking at the source of SimpleDateFormat it seems that 2012-12-21 is actually split into this: year = "2012" month = "-1" day = "2-" The source comments state that a - following a number might either denote a negative number (depending on the locale) or be a delimiter.In your case it seems to be taken as a delimiter, thus day = "2-" results in day = 2, hence the second of November.

Wow, thanks for the explanation! I still don't understand though why -12 months is November, and why -21 days is the 8th of it. I suppose that is an underflow?

I don't see it described anywhere in the docs. – Daniel Dinnyes Jul 28 '11 at 13:21 @Daniel Internally SimpleDateFormat uses Calendar which - as the others already suggested - by default is lenient and thus adjusts negative values that are passed in. – Thomas Jul 28 '11 at 14:09 Thanks for solving the mystery!

– Daniel Dinnyes Jul 28 '11 at 16:38.

You need to call setLenient(false). The default is true and Java tries to convert the string even it does not match 100%.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions