0

I would like to ask what is the most suitable way to create List of Dates for specific year to hold the dates of this year.

I have written the following and it works fine. However,I am not sure that this the most convenient way.

        Calendar cal = new GregorianCalendar(2012, Calendar.JANUARY, 1);
        Date startDate = cal.getTime();

        cal = new GregorianCalendar(2013, Calendar.JANUARY, 1);
        Date endDate = cal.getTime();


        List<Date> dates = new ArrayList<Date>();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(startDate);

        while (calendar.getTime().before(endDate)) {
            Date date= calendar.getTime();
            dates.add(date);
            calendar.add(Calendar.DATE, 1);
        }
Jasonw
  • 5,054
  • 7
  • 43
  • 48
Echo
  • 2,959
  • 15
  • 52
  • 65

2 Answers2

5

You could just simplify that:

int startYear = 2012;
int endYear = 2013;

Calendar cal = new GregorianCalendar(startYear, Calendar.JANUARY, 1);
ArrayList<Date> dates = new ArrayList<Date>();
while(cal.get(Calendar.YEAR) < endYear){
    dates.add(cal.getTime());
    cal.add(Calendar.DATE, 1);
}
rtheunissen
  • 7,347
  • 5
  • 34
  • 65
0

Similar as how to get a list of dates between two dates in java

With Lamma one can easily construct date range:

    for (Date d: Dates.from(2014, 6, 29).to(2014, 7, 1).build()) {
        System.out.println(d);
    }

And the output is:

Date(2014,6,29)
Date(2014,6,30)
Date(2014,7,1)
Community
  • 1
  • 1
Max
  • 2,065
  • 24
  • 20