获取并比较LocalDateTime的小时+分钟与给定小时的最佳解决方案是什么



我正在实施一项服务(任何时候都不去生产(,该服务应接收LocalDateTimeDuration,并应检查给定时间是否在公司工作时间之间(即8:00-22:00(,工作时间应(以某种方式(可配置:

假设我有一个:

public class CompanyWorkingHoursService {
private static final Int OPENING_HOUR = 8;
private static final Int CLOSING_HOUR = 22;
private boolean isMeetingBetweenWorkingHours(LocalDateTime beginningDateTime, Duration duration) {
LocalDateTime endingDateTime = beginningDateTime.plus(duration);
}

我被卡住了。

我可以将OPENING_HOURCLOSING_HOUR的类型更改为我想要的任何类型。我可以从LocalDateTime中得到小时和分钟,但这些都是整数。我不想比较整个日期——我只需要几个小时和几分钟。

我已经找到了一些使用java.util.Date的解决方案,但如果可能的话,我想继续使用LocalDateTime。。。

;最好的";问题是要避免整数。因此,将开放和关闭时间定义为LocalTime,并使用LocalTime:提供的isAfter()isBefore()equals()比较日期

private static final LocalTime OPENING_HOUR = LocalTime.of(8, 0);
private static final LocalTime CLOSING_HOUR = LocalTime.of(22, 0);
private boolean isMeetingBetweenWorkingHours(LocalDateTime beginningDateTime, Duration duration) {
LocalDateTime endingDateTime = beginningDateTime.plus(duration);
return !beginningDateTime.toLocalTime().isBefore(OPENING_HOUR)
&& !endingDateTime.toLocalTime().isAfter(CLOSING_HOUR));
}

如果工作时间应该(以某种方式(可配置,您也可以将它们传递给方法。然后根据这些值和会议日期创建LocalDateTime实例。

可能是这样的:

public static boolean isMeetingBetweenWorkingHours(
LocalDateTime startMeeting, Duration meetingDuration,
int openFrom, int openUntil) { // pass start and end hour of day
/* 
* create the working time hours using the hours of day passed 
* and using the date of the meeting start passed
*/
LocalDateTime startWorkingHours = LocalDateTime.of(startMeeting.toLocalDate(),
LocalTime.of(openFrom, 0));
LocalDateTime endWorkingHours = LocalDateTime.of(startMeeting.toLocalDate(),
LocalTime.of(openUntil, 0));
// calculate the end time of the meeting
LocalDateTime endMeeting = startMeeting.plus(meetingDuration);
// then return if the meeting fully fits into the working time slot
return !startMeeting.isBefore(startWorkingHours)
&& !endMeeting.isAfter(endWorkingHours);
}

最新更新