I have encountered a problem that I don't know how to solve.
I have a list containing dates, as below code:
public static void main(String[] args) {
TreeSet<LocalDate> dates = getDaysBetween("2017-02-01","2017-03-31");
dates.removeAll(getDaysBetween("2017-01-01","2017-02-01"));
dates.removeAll(getDaysBetween("2017-03-01","2017-03-04"));
dates.removeAll(getDaysBetween("2017-03-08","2017-03-08"));
dates.removeAll(getDaysBetween("2017-03-10","2017-03-12"));
dates.removeAll(getDaysBetween("2017-03-14","2017-03-16"));
dates.removeAll(getDaysBetween("2017-03-19","2017-03-19"));
dates.removeAll(getDaysBetween("2017-03-22","2017-03-22"));
}
public static TreeSet<LocalDate> getDaysBetween(String start, String end){
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(start, fmt);
LocalDate endDate = LocalDate.parse(end, fmt);
TreeSet<LocalDate> dates = new TreeSet<LocalDate>();
LocalDate current = startDate;
while (current.isBefore(endDate) || current.equals(endDate)) {
dates.add(current);
current = current.plusDays(1);
}
return dates;
}
class Period {
private Date startDate;
private Date endDate;
}
The criteria for start and end dates are "dates are consecutive (one day of difference between them)", and when they're not consecutive, then another period has started.
In main method, I create a lot dates stored into List, and then remove some dates from that list. Using the left consecutive dates (one day of difference between them) in the list to create a period, and when they're not consecutive, then another period has started.
The periods as follows:
startDate: 2017-02-02, endDate: 2017-02-28
startDate: 2017-03-05, endDate: 2017-03-07
startDate: 2017-03-09, endDate: 2017-03-09
startDate: 2017-03-13, endDate: 2017-03-13
startDate: 2017-03-17, endDate: 2017-03-18
startDate: 2017-03-20, endDate: 2017-03-21
startDate: 2017-03-23, endDate: 2017-03-31
I want to create an algorithm to create these Period objects according to the provided date list.
I'm blocked by this for long time. So far, I have not come up with a good sulotion for this case.