SimpleDateFormat Generates Incorrect Date Time for YYYY-MM-dd HH:mm String
Issue:
Parsing a string in the "YYYY-MM-dd HH:mm" format using SimpleDateFormat yields an unexpected date.
Example:
<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>
Actual Result:
Sun Dec 30 08:30:00 EST 2012
Expected Result:
2013-03-18 08:30:00
Resolution:
The issue lies in the SimpleDateFormat pattern string. The format specifier for year should be "yyyy" instead of "YYYY".
Corrected Code:
<code class="java">SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);</code>
This modification ensures that the year is parsed as a four-digit year, aligning with the expected format of "YYYY-MM-dd HH:mm".
The above is the detailed content of Why Does SimpleDateFormat Generate an Incorrect Date for a \'YYYY-MM-dd HH:mm\' String?. For more information, please follow other related articles on the PHP Chinese website!