Search code examples
javadatesimpledateformat

Calculate previous 12 months from given month - SimpleDateFormat


I am trying to get previous 12 month into an arraylist, from the given month(taken from DB).

List<String> allDates = new ArrayList<String>();    

sqlQuery="select max(date) from Table_Name";

maxDate="Jan-2016"; (Result from Query);

To get previous 12 months from maxDate,where i use SimpleDateFormat.

I want to calculate the previous 12 months from Given Month (maxDate), not from current month, i tried the following code.

//  Parsing maxDate to an integer (say Jan-2016 = 0, Feb-2016= 1)
Date date = new SimpleDateFormat("MMM-yyyy").parse(maxDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int month=cal.get(Calendar.MONTH);
        System.out.println("month : "+month);

// Looping to get previous 12 months from current month.
SimpleDateFormat month_date = new SimpleDateFormat("MMM-yyyy");
          for (int i = 12; i > 0; i--) {
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.MONTH, -i);
                String month_name1 = month_date.format(calendar1.getTime());
                allDates.add(month_name1);
            }
            System.out.println(allDates);

Since months are numbered from (0 - 11) i couldn't achieve it. Please suggest an idea to calculate previous 12 months from given month. Appreciate your help!


Solution

  • The problem is that in the loop you base the computation always from current date not from maxDate.

    List<String> allDates = new ArrayList<>();
    String maxDate = "Jan-2016";
    SimpleDateFormat monthDate = new SimpleDateFormat("MMM-yyyy");
    Calendar cal = Calendar.getInstance();
    cal.setTime(monthDate.parse(maxDate));
    for (int i = 1; i <= 12; i++) {
        String month_name1 = monthDate.format(cal.getTime());
        allDates.add(month_name1);
        cal.add(Calendar.MONTH, -1);
    }
    System.out.println(allDates);
    

    output

    [Jan-2016, Dec-2015, Nov-2015, Oct-2015, Sep-2015, Aug-2015, Jul-2015, Jun-2015, \
     May-2015, Apr-2015, Mar-2015, Feb-2015]
    

    edit Short explanation what the snippet does.

    1. create a Calendar from the given maxDate and assign it to cal
    2. add the string Mon-Year of the current date in cal to the list allDates
    3. substract one month from the calendar cal.add(Calendar.MONTH, -1)
    4. repeat steps 2. and 3. twelve times

    As mentioned by Basil. If you want to process the values in allDates later on as Date / Calendar think about not to generate a list of strings in between.