Here lenient
is used in Java DateFormat
. I checked the doc, but didn't get what it was saying.
Can any body please tell me what is the use of this lenient
, with one real time example where we use it?
Here lenient
is used in Java DateFormat
. I checked the doc, but didn't get what it was saying.
Can any body please tell me what is the use of this lenient
, with one real time example where we use it?
The javadoc clearly states:
So, if you have a pattern and create a date object that strictly matches your pattern, set lenient to
false
. Also,DateFormat
is lenient, by default.Basically,
DateFormat
setsCalendar.setLenient
and the Javadoc states:You can set the date parser as not lenient if you want it to accept strictly a date format you provided. It is well explained in the doc:
And the result:
If date is not lenient it will throw error if you pass out of range date but if is not then it will accept is and fix it . e.g
August 61st
from comment above will become September 30th. Java doc on how to set it . Default is true.DateFormat object is lenient by default.
Leniency (Javadoc - Calendar)
My advice is to always turn lenient off. I cannot think of a case where you want lenient on, and this setting should never have been the default for classes like SimpleDateFormat. Lenient processing can interpret garbage as valid time strings and opens up errors that may be difficult to catch in testing. Also, if you are using lenient to tolerate variations in time format you are going to get burned. For example:
Yields this (your time zone may vary):
This absurd result appears to be the minus one month ("-1"), second day ("2-") of 2010. The zeroth month is December!
Unfortunately, using setLenient(false) does not lead to strict interpretation of the pattern. SimpleDateFormat will tolerate garbage following the pattern match, as discussed here:
SimpleDateFormat.parse() ignores the number of characters in pattern
Also, it is not strict about the number of pattern characters, such as "d" instead of "dd":
Yields:
Also with setLenient(false) "2010/01/5" is accepted with the pattern "yyyy/MM/dd". And data disagreement is ignored, like "1999/2011" with the pattern "yyyy/yyyy" (answer is 2011).
Using SimpleDateFormat to validate date/time strings is sadly unreliable. If you follow the link above you will see some solutions, including a stricter version of SimpleDateFormat written by me!