Home > Java > javaTutorial > body text

Why is My Java Date Conversion Showing the Wrong Month?

Susan Sarandon
Release: 2024-11-05 20:31:02
Original
910 people have browsed it

Why is My Java Date Conversion Showing the Wrong Month?

Incorrect Date Format Conversion: Troubleshooting Date Parsing

Problem: Converting a date in Java from one format to another results in an inaccurate month.

Input and Expected Output:

  • Input date: "2011-12-15"
  • Expected output: "15 December 2011"

Code Sample:

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

Diagnosis:
The immediate issue is within the "fromFormat" variable. In the code, it is mistakenly set to "yyyy-mm-dd" which expects "mm" to represent minutes. However, a date format should use "MM" to denote months.

Solution:

To resolve the issue and obtain the correct month, the "fromFormat" variable should be modified to the following:

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

By making this correction, the program will correctly recognize "MM" as months, ensuring that the date is parsed with the appropriate month value. This will subsequently result in the expected output of "15 December 2011".

The above is the detailed content of Why is My Java Date Conversion Showing 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template