给出错误月份的简单日期格式

时间:2017-10-23 02:41:28

标签: java date java-ee simpledateformat

我试图将日期从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;
}

2 个答案:

答案 0 :(得分:1)

将第一种格式更改为

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

因为DD是一年中的一天。 22肯定是在一月份

答案 1 :(得分:0)

使用此

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

而不是

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