Home >Java >javaTutorial >Why Does My Java SimpleDateFormat Parse 'mm' as Minutes Instead of Months, and How Can I Fix It?

Why Does My Java SimpleDateFormat Parse 'mm' as Minutes Instead of Months, and How Can I Fix It?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 07:16:26365browse

Why Does My Java SimpleDateFormat Parse

SimpleDateFormat Parsing Ambiguity Resolved

The SimpleDateFormat class is used for parsing dates in Java. However, occasional errors can arise due to its strict parsing rules. One common issue is the misinterpretation of month and minute specifications.

In a recent case, a developer encountered an issue where the code:

SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");

String str = "2010-06-13T00:00:00";

Date date = sf.parse(str);

parsed the date as "Wed Jan 13 00:00:00 EST 2010" instead of the expected "Wed Jun 13 00:00:00 EST 2010."

Resolution

The issue lies in the date format string. In the provided format, "mm" represents minutes, while "MM" represents months. To correct this, the developer simply needed to change the format string to:

"yyyy-MM-dd'T'HH:mm:ss"

This ensures that "MM" is used for month, and the code will now correctly parse the date as "Wed Jun 13 00:00:00 EST 2010."

It's crucial to pay attention to the detailed format specifiers provided in the SimpleDateFormat documentation to avoid such parsing errors.

The above is the detailed content of Why Does My Java SimpleDateFormat Parse 'mm' as Minutes Instead of Months, and How Can I Fix It?. 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