I am trying to get a list of months (actually the first days of those months) between two dates in Java but I am not getting the expected results.
The start date is “3/17/2020”, the end date “3/17/2021” and the expected result is as follows:
"01-Mar-2020" "01-Apr-2020" "01-May-2020" "01-Jun-2020" "01-Jul-2020" "01-Aug-2020" "01-Sep-2020" "01-Oct-2020" "01-Nov-2020" "01-Dec-2020" "01-Jan-2021" "01-Feb-2021" "01-Mar-2021"
Here below is the code I am using:
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 = "3/17/2020";
String date2 = "3/17/2021";
DateFormat formater = new SimpleDateFormat("MM/dd/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();
}
DateFormat formaterYd = new SimpleDateFormat("01-MMM-YYYY");
while (beginCalendar.before(finishCalendar)) {
// add one month to date per loop
String date = formaterYd.format(beginCalendar.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
}
}
}
With the above code I am getting the following result:
"01-Jan-2020" "01-Feb-2020" "01-Mar-2020" "01-Apr-2020" "01-May-2020" "01-Jun-2020" "01-Jul-2020" "01-Aug-2020" "01-Sep-2020" "01-Oct-2020" "01-Nov-2020" "01-Dec-2020"
Please help me understand the issue and suggest any solution for the same with java 7.
Advertisement
Answer
Java7 soulution:
public static void main(String[] args) throws ParseException {
DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Date dateFrom = df1.parse("3/17/2020");
Date dateTo = df1.parse("3/17/2021");
final Locale locale = Locale.US;
DateFormat df2 = new SimpleDateFormat("MMM-yyyy", Locale.US);
List<String> months = getListMonths(dateFrom, dateTo, locale, df2);
for (String month : months)
System.out.println(month.toUpperCase(locale));
}
public static List<String> getListMonths(Date dateFrom, Date dateTo, Locale locale, DateFormat df) {
Calendar calendar = Calendar.getInstance(locale);
calendar.setTime(dateFrom);
List<String> months = new ArrayList<>();
while (calendar.getTime().getTime() <= dateTo.getTime()) {
months.add(df.format(calendar.getTime()));
calendar.add(Calendar.MONTH, 1);
}
return months;
}
Output:
MAR-2020 APR-2020 MAY-2020 JUN-2020 JUL-2020 AUG-2020 SEP-2020 OCT-2020 NOV-2020 DEC-2020 JAN-2021 FEB-2021 MAR-2021