Simpledateformat - 为什么 Calendar.MONTH 错误地为 January'16 生成了上个月的值(即 Dec-2015)?

Simpledateformat - Why Calendar.MONTH wrongly generate previous month value(ie Dec-2015) for January'16?

我一直在尝试使用 Simpledateformat 从当月获取过去 12 个月的值。但是对于上个月(即 2015 年 12 月),我总是得到 2016 年 12 月。

calendar.set(Calendar.MONTH, -1); 这应该是 return 2015 年 12 月,但不是。

我不明白其中的逻辑。有人可以解释一下吗?非常感谢您的时间和帮助。

我的代码:

public static void main (String[] args) throws java.lang.Exception
{
    SimpleDateFormat month_date = new SimpleDateFormat("MMM-YYYY");

    Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, -1);


        String month_name = month_date.format(calendar.getTime());
        System.out.println("month_name : "+month_name);

}

输出:

month_name : Dec-2016

要减去月份,您可以这样做:

calendar.add(Calendar.MONTH, -1);

希望对你有帮助。

代码有几个问题。

1) 您应该使用加calendar.add(Calendar.MONTH, -1);来减去月份。

2) 有趣的是在那之后它也会将输出打印为 month_name : Dec-2016 这是因为你的 SimpleDateFormat 有一个问题,即你提到了大写的年份 Y 这是Week year 将其更改为 y 即可。

可以参考SimpleDateFormat文档here.

修改后的代码将是:

public static void main (String[] args) throws java.lang.Exception
    {
         SimpleDateFormat month_date = new SimpleDateFormat("MMM-yyyy");
         Calendar calendar = Calendar.getInstance();
         calendar.add(Calendar.MONTH, -1);

         String month_name = month_date.format(calendar.getTime());
         System.out.println("month_name : "+month_name);
   }