Home >Java >javaTutorial >Why Does SimpleDateFormat Fail to Parse \'YYYY-MM-dd HH:mm\' Despite `setLenient(false)`?

Why Does SimpleDateFormat Fail to Parse \'YYYY-MM-dd HH:mm\' Despite `setLenient(false)`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 06:51:30573browse

Why Does SimpleDateFormat Fail to Parse

SimpleDateFormat Incorrect Date Parsing of "YYYY-MM-dd HH:mm"

Q:

Using SimpleDateFormat, an attempt to parse a string in the format "YYYY-MM-dd HH:mm" to a Date is yielding an incorrect date. Despite setting setLenient(false), the result is still inaccurate. What is the cause of this discrepancy?

A:

The issue lies in the format string used: "YYYY-MM-dd HH:mm". The correct format string for parsing a string in the given format should be "yyyy-MM-dd HH:mm", where "yyyy" denotes the year with four digits.

The documentation for SimpleDateFormat specifies that "the date portion must be in one of the JDK predefined formats, the time portion must be in one of the predefined time formats, and the separator between the date and time can only be one of the predefined separators." Refer to the SimpleDateFormat documentation for further details.

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

By modifying the format string to "yyyy-MM-dd HH:mm", the parsing should produce the correct date and time.

The above is the detailed content of Why Does SimpleDateFormat Fail to Parse \'YYYY-MM-dd HH:mm\' Despite `setLenient(false)`?. 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