Find all month names between two given date in java

You can simply use the Calendar class and iterate from one date to the other one by adding a month at each iteration using myCalendar.add(Calendar.MONTH, 1);.

The Calendar class takes care of avoiding overflows and updating the other fields (here the year) for you.


Per conversation above. Use Calendar and the add method.

I've not tested this but it's about there:

public static List<Date> datesBetween(Date d1, Date d2) {
    List<Date> ret = new ArrayList<Date>();
    Calendar c = Calendar.getInstance();
    c.setTime(d1);
    while (c.getTimeInMillis()<d2.getTime()) {
        c.add(Calendar.MONTH, 1);
        ret.add(c.getTime());
    }
    return ret;
}

Using Joda-Time (since not specified, I assume you could at least have a look at what joda time is):

 LocalDate date1 = new LocalDate("2011-12-12");
 LocalDate date2 = new LocalDate("2012-11-11"); 
 while(date1.isBefore(date2)){
     System.out.println(date1.toString("MMM/yyyy"));
     date1 = date1.plus(Period.months(1));
 }

java.time.YearMonth

While the other answers were good answers when written, they are now outdated. Since Java 8 introduced the YearMonth class, this task has been greatly simplified:

    String date1 = "20/12/2011";
    String date2 = "22/08/2012";

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ROOT);
    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM/uuuu", Locale.ROOT);
    YearMonth endMonth = YearMonth.parse(date2, dateFormatter);
    for (YearMonth month = YearMonth.parse(date1, dateFormatter);
            ! month.isAfter(endMonth);
            month = month.plusMonths(1)) {
        System.out.println(month.format(monthFormatter));
    }

This prints:

Dec/2011
Jan/2012
Feb/2012
Mar/2012
Apr/2012
May/2012
Jun/2012
Jul/2012
Aug/2012

Please supply an appropriate locale for the second call to DateTimeFormatter.ofPattern() to get the month names in your language. And the first call too to be on the safe side.

Tags:

Java