2012-07-30 60 views
0

我想問什麼是最適合的方式來創建特定年份日期列表今年的日期。方便的方法來生成日期

我寫了下面的內容,它工作正常。 但是,我不確定這是最方便的方法。

 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); 
     } 

回答

5

你可以只簡化:

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); 
}