| | |
| | | import lombok.Data; |
| | | import lombok.NoArgsConstructor; |
| | | |
| | | import java.time.Duration; |
| | | import java.time.LocalDateTime; |
| | | import java.util.Comparator; |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | @Data |
| | | @AllArgsConstructor |
| | |
| | | public int compareTo(Calculate o) { |
| | | return start.compareTo(o.start); |
| | | } |
| | | |
| | | public Duration getDuration() { |
| | | return Duration.between(start, end); |
| | | } |
| | | |
| | | public static Duration calculateRemainingDuration(Calculate mainPeriod, Calculate... excludedPeriods) { |
| | | List<Calculate> remainPeriods = new ArrayList<>(); |
| | | remainPeriods.add(mainPeriod); |
| | | |
| | | for (Calculate excluded : excludedPeriods) { |
| | | List<Calculate> newRemaining = new ArrayList<>(); |
| | | for (Calculate remain : remainPeriods) { |
| | | newRemaining.addAll(subtractPeriod(remain, excluded)); |
| | | } |
| | | remainPeriods = newRemaining; |
| | | } |
| | | |
| | | // 计算所有剩余时间段的总时长 |
| | | Duration total = Duration.ZERO; |
| | | for (Calculate period : remainPeriods) { |
| | | total = total.plus(period.getDuration()); |
| | | } |
| | | |
| | | return total; |
| | | } |
| | | |
| | | private static List<Calculate> subtractPeriod(Calculate main, Calculate toSubtract) { |
| | | List<Calculate> result = new ArrayList<>(); |
| | | |
| | | // 没有重叠的情况 |
| | | if (main.getEnd().compareTo(toSubtract.getStart()) <= 0 || |
| | | main.getStart().compareTo(toSubtract.getEnd()) >= 0) { |
| | | result.add(main); |
| | | return result; |
| | | } |
| | | |
| | | // 时间段完全包含在要减去的时间段中 |
| | | if (main.getStart().compareTo(toSubtract.getStart()) >= 0 && |
| | | main.getEnd().compareTo(toSubtract.getEnd()) <= 0) { |
| | | return result; // 返回空列表 |
| | | } |
| | | |
| | | // 时间段部分重叠 |
| | | if (main.getStart().compareTo(toSubtract.getStart()) < 0) { |
| | | // 左边有剩余 |
| | | result.add(new Calculate(main.getStart(), toSubtract.getStart())); |
| | | } |
| | | |
| | | if (main.getEnd().compareTo(toSubtract.getEnd()) > 0) { |
| | | // 右边有剩余 |
| | | result.add(new Calculate(toSubtract.getEnd(), main.getEnd())); |
| | | } |
| | | |
| | | return result; |
| | | } |
| | | } |