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:
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(); }
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";
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!