Friday, May 6, 2016

for-looping dates

Thanks to self-less people in StackOverflow... learned another new trick.. looping through java.util.Date. http://stackoverflow.com/questions/4534924/how-to-iterate-through-range-of-dates-in-java. No I don't use java 8. If you let people use lambda stuff they go crazy with it.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2010-12-20");
Date endDate = formatter.parse("2010-12-26");

Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);

for (Date date = start.getTime(); start.before(end); 
    start.add(Calendar.DATE, 1), 
    date = start.getTime()) {

    // Do your job here with `date`.
    System.out.println(date);
}
..and yes, Java pre-8 date handling is incredibly clumsy. Can't do anything unless you put it into a Calendar. Why can't java.util.Date have the ability to do that?

No comments: