How to add to the date list? it's overwrite. How can I solve it?
List<LeaveDetails> leaveList=leaveDetailsService.getleavedatetesting(3);
List<Date> datelist = new ArrayList<Date>();
System.out.println("leave list is --> "+leaveList.toString());
for (LeaveDetails lds: leaveList){
Date startd = new Date();
startd= lds.getStartDate();
Date endd = new Date();
endd = lds.getEndDate();
System.out.println("start date is ---> "+startd);
System.out.println("end date is ---> "+endd);
for (int i = startd.getDate() ; i<=(endd.getDate()+1);i++){
startd.setDate(i);
datelist.add(startd);
System.out.println(i+"--datelist ---> "+datelist.toString());
}
}
System.out.println("date list is ---> "+datelist.toString());
I want the list like this including startdate and enddate-->example date 2,3,4,8,9,10,11.
In console, I got this,
start date is ---> 2015-12-02
end date is ---> 2015-12-04
2--datelist ---> [2015-12-02]
3--datelist ---> [2015-12-03, 2015-12-03]
4--datelist ---> [2015-12-04, 2015-12-04, 2015-12-04]
5--datelist ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05]
start date is ---> 2015-12-08
end date is ---> 2015-12-11
8--datelist ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05, 2015-12-08]
9--datelist ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05, 2015-12- 09, 2015-12-09]
10--datelist ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05, 2015-12-10, 2015-12-10, 2015-12-10]
11--datelist ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05, 2015-12-11, 2015-12-11, 2015-12-11, 2015-12-11]
12--datelist ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05, 2015-12-12, 2015-12-12, 2015-12-12, 2015-12-12, 2015-12-12]
date list is ---> [2015-12-05, 2015-12-05, 2015-12-05, 2015-12-05, 2015-12-12, 2015-12-12, 2015-12-12, 2015-12-12, 2015-12-12]
-------------------------------
Look at this loop:
for (int i = startd.getDate() ; i<=(endd.getDate()+1);i++){
startd.setDate(i);
datelist.add(startd);
System.out.println(i+"--datelist ---> "+datelist.toString());
}
You're adding a reference to the same Date
object several times, and mutating it on each iteration. You're also assuming that the dates are in the same month, and you're using deprecated methods of Date
.
Given these problems, you'd be much better off using LocalDate
either from Joda Time if you're using Java 7 or earlier, or from java.time
if you're using Java 8.
LocalDate
is immutable, so it's harder to accidentally end up adding the same reference multiple times - and it really represents just a date.
See more on this question at Stackoverflow