Home  >  Article  >  Java  >  Why does SimpleDateFormat produce the wrong date and time when parsing \"YYYY-MM-dd HH:mm\"?

Why does SimpleDateFormat produce the wrong date and time when parsing \"YYYY-MM-dd HH:mm\"?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 19:15:031032browse

Why does SimpleDateFormat produce the wrong date and time when parsing

SimpleDateFormat Producing Incorrect Date and Time When Parsing "YYYY-MM-dd HH:mm"

When attempting to convert a String representation of a date and time in the format "YYYY-MM-dd HH:mm" to a Date object using SimpleDateFormat, incorrect results may be obtained. As illustrated below, the code produces an unexpected output:

<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>

The expected output should be "Thu Mar 18 08:30:00 EST 2013", but the code mistakenly produces "Sun Dec 30 08:30:00 EST 2012".

The cause of the issue lies in the mistyped YYYY pattern in the SimpleDateFormat constructor. The correct pattern for the specified date and time format is yyyy, with lowercase y for years.

To resolve this issue, modify the SimpleDateFormat pattern as follows:

<code class="java">SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);</code>

By updating the pattern, the SimpleDateFormat object will now correctly parse the date and time string, resulting in the desired output of "Thu Mar 18 08:30:00 EST 2013".

It's important to note that while Lenient is off in this code, it is generally not recommended to turn it off. In most cases, it is better to handle parsing errors gracefully rather than potentially parsing incorrect data.

The above is the detailed content of Why does SimpleDateFormat produce the wrong date and time when parsing \"YYYY-MM-dd HH:mm\"?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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