How to get a list of months and years between two dates

I need your help getting a list of months and years in a String between two dates. The user enters two dates in String format:

String date1 ="JAN-2015"; String date2 ="APR-2015"; 

Thus, the result should be:

  • Jan-2015
  • February 2015
  • MAR-2015

I tried using the following code, but this gave me the wrong results:

 List<Date> dates = new ArrayList<Date>(); String str_date ="JAN-2015"; String end_date ="APR-2015"; DateFormat formatter ; formatter = new SimpleDateFormat("MMM-yyyy"); Date startDate = formatter.parse(str_date); Date endDate = formatter.parse(end_date); long endTime =endDate.getTime() ; long curTime = startDate.getTime(); while (curTime <= endTime) { dates.add(new Date(curTime)); curTime ++; } for(int i=0;i<dates.size();i++){ Date lDate =(Date)dates.get(i); String ds = formatter.format(lDate); System.out.println(ds); } 
+5
source share
2 answers

Using the smallest possible code and basic java libraries and getting the result you requested. Thus, you can change the variables date1 and date2.

 import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class Main { public static void main(String[] args) { String date1 = "JAN-2015"; String date2 = "APR-2015"; DateFormat formater = new SimpleDateFormat("MMM-yyyy"); Calendar beginCalendar = Calendar.getInstance(); Calendar finishCalendar = Calendar.getInstance(); try { beginCalendar.setTime(formater.parse(date1)); finishCalendar.setTime(formater.parse(date2)); } catch (ParseException e) { e.printStackTrace(); } while (beginCalendar.before(finishCalendar)) { // add one month to date per loop String date = formater.format(beginCalendar.getTime()).toUpperCase(); System.out.println(date); beginCalendar.add(Calendar.MONTH, 1); } } } 
+5
source

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

All Articles