【问题标题】:simple date format giving wrong month [duplicate]给出错误月份的简单日期格式[重复]
【发布时间】:2017-10-23 02:41:27
【问题描述】:

我试图将日期从 yyyy-MM-dd 格式转换为 yyyy-MM 格式,当我使用输入“2012-10-22”运行以下代码时,它给我的输出是 2012-JAN 而不是2012 年 10 月。有什么想法我做错了吗?

  public static String dateFormatter(String presentDate)
     {
     String formattedDate = "";
     SimpleDateFormat tempFormat = new SimpleDateFormat("YYYY-MM-DD");
     SimpleDateFormat finalFormat = new SimpleDateFormat("YYYY-MMM");

     try {
        Date currentFormat = tempFormat.parse(presentDate);
        formattedDate = finalFormat.format(currentFormat);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    return formattedDate;
}

【问题讨论】:

  • 大小写对于 SimpleDateFormat 掩码非常重要
  • DateFormat 的所有问题一样,请先咨询JavaDocsY“周年”
  • 仅供参考,这段代码使用了麻烦的旧日期时间类,这些类现在是遗留的,被现代 java.time 类所取代。
  • 使用 java.time 类:YearMonth.from( LocalDate.parse( "2012-10-22" ) ).format( DateTimeFormatter.ofPattern( "uuuu-MMM" , Locale.US ) )2012-Octcode run live at IdeOne.com

标签: java date jakarta-ee simpledateformat


【解决方案1】:

将第一种格式改为

SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd");

DD 是一年中的某一天。 22肯定是1月份

【讨论】:

    【解决方案2】:

    使用这个

    SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd");
    

    代替

    SimpleDateFormat tempFormat = new SimpleDateFormat("YYYY-MM-DD");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多