Generating Dates Between Start and End in 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 { startDate.setTime(DATE_FORMAT.parse("2012/08/01")); endDate.setTime(DATE_FORMAT.parse("2012/08/10")); ArrayList<String> includedDates = new ArrayList<String>(); while(!startDate.equals(endDate)) { String date = DATE_FORMAT.format(startDate.getTime()); includedDates.add(date); startDate.add(Calendar.DATE, 1); } includedDates.add(DATE_FORMAT.format(endDate.getTime())); for(String date : includedDates) { System.out.println(date); } } 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: