Simpledateformat - Why does Calendar.MONTH erroneously generate the value of the previous month (i.e. Dec-2015) for January'16?

I am trying to get the last 12 months from the current month using Simpledateformat. But for the previous month (i.e. December-2015) I always get Dec-2016.

calendar.set (Calendar.MONTH, -1); He is expected to return by December 2015, but he is not.

I do not understand the logic. Can someone explain. Thanks so much for your time and help.

My code is:

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

}

Output:

month_name : Dec-2016
+4
source share
2 answers

There are a couple of code issues.

1) You must use add calendar.add(Calendar.MONTH, -1);to subtract the month.

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

, :

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

, .

+2

Source: https://habr.com/ru/post/1626515/


All Articles