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:
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.");
}
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."
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
By making this adjustment, the code will parse the "YYYY-MM-dd HH:mm" string correctly. Consult the SimpleDateFormat documentation for further information.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3