Home > Java > javaTutorial > Why is My Java Date Conversion Producing the Wrong Month?

Why is My Java Date Conversion Producing the Wrong Month?

DDD
Release: 2024-11-06 08:14:02
Original
1188 people have browsed it

Why is My Java Date Conversion Producing the Wrong Month?

Java Date Format Conversion Issue: Incorrect Month Rendering

Problem Encountered

When attempting to convert a date from one format to another using Java, some users have encountered an issue where the month is incorrectly rendered. Specifically, when converting from a format like "yyyy-mm-dd" to "dd MMMM yyyy," the resulting month appears as the following month (e.g., "01/12/21" becomes "01 January 2021" instead of "01 December 2021").

Incorrect Format Specification

The root cause of this issue lies in the incorrect specification of the fromFormat string. In the example provided, the fromFormat is defined as "yyyy-mm-dd." However, "mm" in the Java SimpleDateFormat class denotes minutes, not months. To correctly represent months, the format specifier should be "MM."

Corrected Code

To resolve this issue, the code should be updated as follows:

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

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

    DateFormat toFormatter = new SimpleDateFormat(toFormat);
    String result = toFormatter.format(date);
    
    System.out.println(result); // Prints "15 December 2011"
} catch (ParseException e) {
    e.printStackTrace();
}
Copy after login

The above is the detailed content of Why is My Java Date Conversion Producing the Wrong 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