简单日期格式 - 为什么 Calendar.MONTH 错误地生成 1 月 16 日的上个月值(即 Dec-2015)?



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

calendar.set(Calendar.MONTH, -1);这应该返回 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文档。

修改后的代码将是:

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);
   }

最新更新