import java.time.*;
import java.time.temporal.ChronoUnit;
public class WorkTimeCalculator {
private static final LocalTime MIN_START = LocalTime.of(8, 30);
private static final Duration DAILY_MAX = Duration.ofHours(8);
private static final Duration MINIMUM_WORK_TIME = Duration.ofMinutes(6);
public static Duration calculateWorkDuration(LocalDateTime start, LocalDateTime end) {
if (end.isBefore(start)) return Duration.ZERO;
Duration total = Duration.ZERO;
LocalDate currentDate = start.toLocalDate();
while (!currentDate.isAfter(end.toLocalDate())) {
DayOfWeek day = currentDate.getDayOfWeek();
if (day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY) {
currentDate = currentDate.plusDays(1);
continue;
}
Duration workDuration = Duration.ZERO;
// 시작일 처리
if (currentDate.equals(start.toLocalDate())) {
LocalTime from = start.toLocalTime().isBefore(MIN_START) ? MIN_START : start.toLocalTime();
LocalTime to = currentDate.equals(end.toLocalDate()) ? end.toLocalTime() : LocalTime.MAX;
if (to.isBefore(from)) {
workDuration = Duration.ZERO;
} else {
workDuration = Duration.between(from, to);
}
}
// 종료일 처리
else if (currentDate.equals(end.toLocalDate())) {
LocalTime from = MIN_START;
LocalTime to = end.toLocalTime();
if (to.isAfter(from)) {
workDuration = Duration.between(from, to);
}
}
// 중간일 처리
else {
workDuration = DAILY_MAX;
}
// 하루 최대 8시간 제한
if (workDuration.compareTo(DAILY_MAX) > 0) {
workDuration = DAILY_MAX;
}
total = total.plus(workDuration);
currentDate = currentDate.plusDays(1);
}
// 최소 시간 보정
if (total.compareTo(MINIMUM_WORK_TIME) < 0) {
total = MINIMUM_WORK_TIME;
}
return total;
}
// 예시 테스트
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2025, 5, 15, 19, 0);
LocalDateTime end = LocalDateTime.of(2025, 5, 16, 20, 0);
Duration result = calculateWorkDuration(start, end);
System.out.println("작업시간 (분): " + result.toMinutes());
}
}
2025. 5. 19. 13:53