使用SimpleDateFormat转换日期时月份始终显示为JANUARY问题咨询
Hey there, let's get to the bottom of why your date parsing keeps spitting out January every time!
问题根源
The core issue here is a case-sensitive format symbol mistake:
- You used
"yyyy-mm-dd"to parse the date string"2017-12-29", but lowercasemmin SimpleDateFormat stands for minutes, not months. - The correct symbol for months is uppercase
MM.
Since the 12 in your input string was being interpreted as minutes instead of December, the month field never got properly set—so it defaulted to JANUARY (the first month of the year).
Also, a quick side note: You used YYYY in your output formatter, which represents the Week Year (a year defined by week boundaries, which might differ from the Gregorian calendar year). For standard calendar years, you should use lowercase yyyy.
修正后的代码
public static void main(String args[]) { String date = "2017-12-29"; // 替换mm为MM,正确解析月份 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 替换YYYY为yyyy,正确输出公历年份 SimpleDateFormat dateFormatter = new SimpleDateFormat("MMMM dd, yyyy"); try { Date startEntryDate = formatter.parse(date); System.out.println(dateFormatter.format(startEntryDate)); // 现在会输出:December 29, 2017 } catch (ParseException e) { e.printStackTrace(); } }
关键格式符区分小提示
To avoid similar issues in the future, remember these case-sensitive rules for SimpleDateFormat:
MM= Month (01-12)mm= Minutes (00-59)yyyy= Gregorian calendar yearYYYY= Week-based yeardd= Day of month (01-31)HH= Hour in 24-hour format (00-23)hh= Hour in 12-hour format (01-12)
内容的提问来源于stack exchange,提问作者Mr.Aw

