You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SimpleDateFormat转换日期时月份始终显示为JANUARY问题咨询

解决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 lowercase mm in 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 year
  • YYYY = Week-based year
  • dd = 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:50:45