If your version of Java is <8, you can use Calendar as follows:
private final static DateFormat formatter = new SimpleDateFormat("MMM-yyyy", Locale.ENGLISH); public static void main(String[] args) throws ParseException { Calendar startDate = stringToCalendar("Jan-2015"); Calendar endDate = stringToCalendar("Apr-2015"); while (startDate.before(endDate)) { System.out.println(formatter.format(startDate.getTime())); startDate.add(Calendar.MONTH, 1); } } private static Calendar stringToCalendar(String string) throws ParseException { Date date = formatter.parse(string); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar; }
If you have the luxury of Java 8, the code becomes simpler:
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy", Locale.ENGLISH); YearMonth startDate = YearMonth.parse("Jan-2015", formatter); YearMonth endDate = YearMonth.parse("Apr-2015", formatter); while(startDate.isBefore(endDate)) { System.out.println(startDate.format(formatter)); startDate = startDate.plusMonths(1); } }
source share