Search code examples
javadatecalendarlocaldate

How to get last three months first date and last date based on current date including current date in java?


I want to categorize values based on months so to filter those values required 1st & last date of last three months based on current month including current month values. Here how many last months is parameter. I wanted list of all months 1st date and last date. Any logic for the same will be helpful.

for example:-

     //     parameters 
          int lastMonths = 3;
          date currentDate= 26-04-2019;

 //expected output
 current month is 04-2019 ,1st date is 1-04-2019 and last date is 30-04-2019 
 previous month is 03-2019, 1st date is 01-03-2019 and last date is 31-03-2019
 previous month is 02-2019, 1st date is 01-02-2019 and last date is 28-02-2019

Solution

  • Use java.util.Calendar for addition and subraction in date

    and

    java.text.DateFormat to format date

        DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
        DateFormat monthFormat = new SimpleDateFormat("MM-yyyy", Locale.US);
        Calendar cal = Calendar.getInstance();
        cal.setTime(format.parse("26-04-2019"));
        for (int i = 0; i < 3; i++){
            System.out.println("currentDate: " + monthFormat.format(cal.getTime())); // print current month
    
            cal.set(Calendar.DAY_OF_MONTH, 1);
            System.out.println("first date: " + format.format(cal.getTime())); // print first date
    
            cal.add(Calendar.MONTH, 1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.add(Calendar.DATE, -1);
    
            System.out.println("last date: " + format.format(cal.getTime())); // print last date
    
    
            cal.add(Calendar.MONTH, -1);
        }