This question already has answers here: Determine Whether Two Date Ranges Overlap                                                                    (34个答案)                                                                                        4年前关闭。                                我正在努力解决以下问题:在我的应用中,我想检查当前日期时间是否来自LocalDateTime.now()是在一周的某些特定日期范围内,例如在星期五和星期日之间。例:日期时间窗口是从星期五20:00到星期日20:00。当我在星期四22:00 *检查当前日期时,答案应该为false,但是当我在**星期六8:00进行检查时,答案应该为true。我可以使用DayOfWeek方法通过java.time API中的compareTo()类并分别比较小时和分钟来实现这一点,但是我想知道是否还有更好的方法,尤其是当天数跨度时两周以上(例如,下周的星期五至下周一)?在此先感谢您的任何建议或帮助。 最佳答案 因为您想将LocalDateTime与DayOfWeek + LocalTime进行比较,或者更确切地说是检查它是否在两个DayOfWeek + LocalTime对之间,所以一个助手类可能是不错的选择:public final class DayOfWeekTimeRange { private final DayOfWeek fromDay; private final LocalTime fromTime; private final DayOfWeek toDay; private final LocalTime toTime; private final boolean inverted; public DayOfWeekTimeRange(DayOfWeek fromDay, LocalTime fromTime, DayOfWeek toDay, LocalTime toTime) { this.fromDay = fromDay; this.fromTime = fromTime; this.toDay = toDay; this.toTime = toTime; this.inverted = compare(this.fromDay, this.fromTime, this.toDay, this.toTime) > 0; } public boolean inRange(LocalDateTime dateTime) { return inRange(dateTime.getDayOfWeek(), dateTime.toLocalTime()); } public boolean inRange(DayOfWeek day, LocalTime time) { boolean fromOk = compare(day, time, this.fromDay, this.fromTime) >= 0; // Lower-inclusive boolean toOk = compare(day, time, this.toDay , this.toTime ) < 0; // Upper-exclusive return (this.inverted ? fromOk || toOk : fromOk && toOk); } private static int compare(DayOfWeek day1, LocalTime time1, DayOfWeek day2, LocalTime time2) { int cmp = day1.compareTo(day2); if (cmp == 0) cmp = time1.compareTo(time2); return cmp; }}测试// Fri 10:00 PM to Sun 10:00 PMDayOfWeekTimeRange range = new DayOfWeekTimeRange(DayOfWeek.FRIDAY, LocalTime.of(20,0), DayOfWeek.SUNDAY, LocalTime.of(20,0));System.out.println(range.inRange(LocalDateTime.of(2015, 11, 12, 22, 0))); // Thu Nov. 12 2015 at 10:00 PMSystem.out.println(range.inRange(LocalDateTime.of(2015, 11, 14, 8, 0))); // Sat Nov. 14 2015 at 8:00 AMSystem.out.println(range.inRange(LocalDateTime.of(2015, 11, 16, 15, 0))); // Mon Nov. 16 2015 at 3:00 PM// Fri 10:00 PM to Mon 10:00 PMrange = new DayOfWeekTimeRange(DayOfWeek.FRIDAY, LocalTime.of(20,0), DayOfWeek.MONDAY, LocalTime.of(20,0));System.out.println(range.inRange(LocalDateTime.of(2015, 11, 12, 22, 0))); // Thu Nov. 12 2015 at 10:00 PMSystem.out.println(range.inRange(LocalDateTime.of(2015, 11, 14, 8, 0))); // Sat Nov. 14 2015 at 8:00 AMSystem.out.println(range.inRange(LocalDateTime.of(2015, 11, 16, 15, 0))); // Mon Nov. 16 2015 at 3:00 PM输出量falsetruefalsefalsetruetrue另类当然,如果对DayOfWeek + LocalTime进行了大量处理,则应考虑实现自己的LocalDayOfWeekTime类,将两者结合起来,同样的方式LocalDateTime只是结合在一起的LocalDate + (而且,请检查一下自己)。关于java - Java:检查当前日期是否在特定日期范围内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33701048/
10-12 01:54