"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does SimpleDateFormat Incorrectly Parse \"YYYY-MM-dd HH:mm\"?

Why Does SimpleDateFormat Incorrectly Parse \"YYYY-MM-dd HH:mm\"?

Published on 2024-12-21
Browse:265

Why Does SimpleDateFormat Incorrectly Parse \

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.

Latest tutorial More>

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