Determine whether there are intervals in multiple time periods
Entity content
public class DateRangeStr { @JsonFormat(shape = , pattern="yyyy-MM", timezone = "GMT+8") private String startDate;//Format: yyyy-MM-dd @JsonFormat(shape = , pattern="yyyy-MM", timezone = "GMT+8") private String endDate;//Format: yyyy-MM-dd}
Main method content
//Judge whether there are time intervals for multiple time periods. True without intervals. False with intervals. public boolean hasNoGaps(List<DateRangeStr> sortedStrRanges) { DateTimeFormatter formatter = ("yyyy-MM-dd"); if (sortedStrRanges == null || () <= 0) return false; if (() == 1) return true; List<DateRange> timePeriods = new ArrayList<>(); for (DateRangeStr ss : sortedStrRanges) { LocalDate startDate = ((), formatter); LocalDate endDate = ((), formatter); DateRange dr = new DateRange(); (startDate); (endDate); (dr); } (timePeriods, (DateRange::getStartDate)); LocalDate previousEndDate = (0).getEndDate(); for (int i = 1; i < (); i++) { DateRange currentPeriod = (i); if ((())) { // The start date of the current time period is earlier than the end date of the previous time period, and there is overlap, which is not necessarily a problem // But we still use the end date of the current time period as the new previousEndDate previousEndDate = (); } else if ((!(()) && !(1L).isEqual(()))) { // The interval was found return false; } else { // There is no interval between adjacent time periods previousEndDate = (); } } return true; // All time periods have been traversed and no time intervals have been found }
Determine whether the time period set overlaps with a certain time period
Entity content
public class TimeInterval { @JsonFormat(shape = , pattern="yyyy-MM", timezone = "GMT+8") private String start; @JsonFormat(shape = , pattern="yyyy-MM", timezone = "GMT+8") private String end; }
Main method content
private static YearMonth parseYearMonth(String input) { try { return (input, MONTH_FORMATTER); } catch (Exception e) { throw new IllegalArgumentException("Invalid date format: " + input, e); } } public static boolean overlapsOrContainedInIntervals(List<TimeInterval> intervals, String startDate,String endDate) { YearMonth yearMonthAStart = parseYearMonth(startDate); YearMonth yearMonthAEnd = parseYearMonth(endDate); for (TimeInterval interval : intervals) { YearMonth start = parseYearMonth(()); YearMonth end = parseYearMonth(()); // Check for overlap or inclusion if (!(yearMonthAEnd) && !(yearMonthAStart)) { return true; } } return false; }
This is the article about the summary of Java's method of judging whether multiple time periods overlap. For more related content on judging whether time periods overlap, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!