I am trying to generate a list of dates from a given start and end date. I found the solution in stack overflow . But, the code gives the distribution starting from the month of January. I am unable to find why. Please help me out.
starting , ending are String with format 'yyyy-mm-dd' . duration is the Arraylist I am using to store the dates.
List<Date> duration = new ArrayList<Date>();
List<Date> date_req = new ArrayList<Date>();
Calendar start = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date date_st = formatter.parse(starting);
Date date_en = formatter.parse(ending);
int init=0;
start.setTime(date_st);
Calendar end = Calendar.getInstance();
end.setTime(date_en);
end.add(Calendar.DAY_OF_YEAR, 1); //Add 1 day to endDate to make sure endDate is included into the final list
while (start.before(end)) {
duration.add(init,start.getTime());
start.add(Calendar.DAY_OF_YEAR, 1);
init=init+1;
}
System.out.println(duration);
Thanks.
Your format should be DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd")
Using mm for Month is the reason you get your year starting from JAN
mm
代表分钟,几个月则必须使用MM
。
Your code works with minor changes as below:
public static void main(String[] args) throws ScriptException,
FileNotFoundException, ParseException {
List<Date> duration = new ArrayList<Date>();
String starting = "2014-04-01";
String ending = "2014-04-30";
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
Date date_st = formatter.parse(starting);
Date date_en = formatter.parse(ending);
int init = 0;
Calendar start = Calendar.getInstance();
start.setTime(date_st);
Calendar end = Calendar.getInstance();
end.setTime(date_en);
end.add(Calendar.DAY_OF_YEAR, 1); // Add 1 day to endDate to make sure
// endDate is included into the
// final list
while (start.before(end)) {
duration.add(start.getTime());
start.add(Calendar.DAY_OF_YEAR, 1);
}
for (Date date : duration) {
System.out.println(date);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.