Home > Java > javaTutorial > Why Does SimpleDateFormat Generate an Incorrect Date for a \'YYYY-MM-dd HH:mm\' String?

Why Does SimpleDateFormat Generate an Incorrect Date for a \'YYYY-MM-dd HH:mm\' String?

Patricia Arquette
Release: 2024-11-02 20:43:02
Original
457 people have browsed it

Why Does SimpleDateFormat Generate an Incorrect Date for a

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template