Generating Dates Between Start and End in Java

Posted on August 11, 2012 at 13:14 Java

Yesterday I had to generate a list of dates given two inputs. Having no Internet connection yet, I eagerly searched for help through my Android phone. Stack Overflow would’ve instantly helped me if I didn’t leave immediately after reading “Joda Time”. The thought of not needing some library for such an ideally simple task was simply there. Then there was this, which compiled but never ran. :faint:

In my case, the checking that the end date should be greater than the start date was already handled somewhere else so I already skipped it. Also, instead of actual Dates, I only needed Strings (but I do intend to convert this into a generic utility class). So, yeah, here you go:

final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");
Calendar startDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();

try {

   ArrayList<String> includedDates = new ArrayList<String>();

   while(!startDate.equals(endDate)) {
      String date = DATE_FORMAT.format(startDate.getTime());
      startDate.add(Calendar.DATE, 1);
   } includedDates.add(DATE_FORMAT.format(endDate.getTime()));

   for(String date : includedDates) {
} catch(Exception e) {}

Today I checked back on the supposedly second working solution I cited above, copy-pasted the code, and successfully ran it. :wtf:

Say What?

Website: (optional)