Home > Java > javaTutorial > Why does my Java date conversion result in an incorrect month?

Why does my Java date conversion result in an incorrect month?

DDD
Release: 2024-11-10 05:21:02
Original
311 people have browsed it

Why does my Java date conversion result in an incorrect month?

Java Date Format Conversion Issue: Incorrect Month in Conversion

In Java, when converting dates between different formats, it's essential to use the correct format specifiers to ensure accurate conversions. In this case, the issue arises from an incorrect format specifier in the input date format string.

Problem:

The following code snippet attempts to convert a date from the format "yyyy-mm-dd" to the format "dd MMMM yyyy". However, the resulting month conversion is incorrect.

String dateStr = "2011-12-15";
String fromFormat = "yyyy-mm-dd";
String toFormat = "dd MMMM yyyy";

try {
    DateFormat fromFormatter = new SimpleDateFormat(fromFormat);
    Date date = (Date) fromFormatter.parse(dateStr);

    DateFormat toformatter = new SimpleDateFormat(toFormat);
    String result = toformatter.format(date);
} catch (ParseException e) {
    e.printStackTrace();
}
Copy after login

Expected Result:

"15 December 2011"

Actual Result:

"15 January 2011"

Incorrect Format Specifier:

The problem is caused by the use of "mm" in the input date format string. In Java SimpleDateFormat, "mm" represents minutes, not months. To specify months, the correct format specifier is "MM".

Solution:

To fix this issue, simply update the input date format string to use "MM" for months:

String fromFormat = "yyyy-MM-dd";
Copy after login

Correct Result:

After making this change, the code snippet will produce the correct month conversion: "15 December 2011".

The above is the detailed content of Why does my Java date conversion result in an incorrect month?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template