SimpleDateFormat Parses "YYYY-MM-dd HH:mm" Incorrectly
When attempting to parse a string in the format "YYYY-MM-dd HH:mm" to a Date, some developers encounter unexpected date results. This occurs when using the SimpleDateFormat class with the lenient setting set to false.
The following code snippet demonstrates the issue:
<code class="java">Date newDate = null; String dateTime = "2013-03-18 08:30"; SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm", Locale.ENGLISH); df.setLenient(false); try { newDate = df.parse(dateTime); } catch (ParseException e) { throw new InvalidInputException("Invalid date input."); }</code>
This code produces an incorrect date:
Sun Dec 30 08:30:00 EST 2012 (wrong)
To resolve this issue, verify that the year format specified in the SimpleDateFormat pattern is lowercase "yyyy" instead of uppercase "YYYY."
<code class="java">SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);</code>
By making this adjustment, the code will parse the "YYYY-MM-dd HH:mm" string correctly. Consult the SimpleDateFormat documentation for further information.
The above is the detailed content of Why Does SimpleDateFormat Incorrectly Parse \'YYYY-MM-dd HH:mm\'?. For more information, please follow other related articles on the PHP Chinese website!