First of all, use LocalDate
for handling dates. Whenever you deal with dates/times, you should strongly consider using java.time
over String
s. You can convert String
s to LocalDate
s using LocalDate.parse
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(fromDate, formatter);
LocalDate endDate = LocalDate.parse(toDate, formatter);
Then, you can just add one day over and over until you reach the same date:
for(LocalDate date = startDate; !endDate.isBefore(date); date = date.plusDays(1)){
dates.add(date.format(formatter));
//dates.add(date);//if you want to work with a List<LocalDate>
}
Summing up, you can use it in your method like this:
public List<String> getDatesBetween(@NotEmpty String fromDate, @NotEmpty String toDate) throws Exception {
List<String> dates = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(fromDate, formatter);
LocalDate endDate = LocalDate.parse(toDate, formatter);
for(LocalDate date = startDate; !endDate.isBefore(date); date = date.plusDays(1)){
dates.add(date.format(formatter));
}
return dates;
}
As, shmosel mentioned in the comments, LocalDate
uses the ISO_LOCAL_DATE
by default so you don't have to provide a DateTimeFormatter
in your case:
public List<String> getDatesBetween(@NotEmpty String fromDate, @NotEmpty String toDate) throws Exception {
List<String> dates = new ArrayList<>();
LocalDate startDate = LocalDate.parse(fromDate);
LocalDate endDate = LocalDate.parse(toDate);
for(LocalDate date = startDate; !endDate.isBefore(date); date = date.plusDays(1)){
dates.add(date.toString());
}
return dates;
}