java 1.传入时间段列表(格式为hh:mm-hh:mm)2.传入日期时间 请计算给定分钟后的日期时间 只考虑工作时段
时间: 2023-12-14 15:36:03 浏览: 117
以下是Java代码示例实现,假设工作时间为每天的 9:00 - 18:00:
```java
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.ArrayList;
public class WorkTimeCalculator {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
public static LocalDateTime calculate(LocalDateTime startDateTime, int minutes, List<String> workHours) {
// 将时间段转换为 LocalTime 类型
List<LocalTime[]> workTimeRanges = new ArrayList<>();
for (String workHour : workHours) {
String[] tokens = workHour.split("-");
LocalTime startTime = LocalTime.parse(tokens[0], FORMATTER);
LocalTime endTime = LocalTime.parse(tokens[1], FORMATTER);
workTimeRanges.add(new LocalTime[]{startTime, endTime});
}
// 计算结束时间
LocalDateTime endDateTime = startDateTime.plusMinutes(minutes);
while (!isWorkTime(endDateTime.toLocalTime(), workTimeRanges)) {
endDateTime = endDateTime.plusMinutes(1);
}
return endDateTime;
}
private static boolean isWorkTime(LocalTime time, List<LocalTime[]> workTimeRanges) {
for (LocalTime[] range : workTimeRanges) {
if (time.isAfter(range[0]) && time.isBefore(range[1])) {
return true;
}
}
return false;
}
}
```
调用示例:
```java
List<String> workHours = new ArrayList<>();
workHours.add("09:00-12:00");
workHours.add("13:00-18:00");
LocalDateTime startDateTime = LocalDateTime.of(2021, 9, 1, 10, 30);
int minutes = 90;
LocalDateTime endDateTime = WorkTimeCalculator.calculate(startDateTime, minutes, workHours);
System.out.println(endDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
```
输出结果为:
```
2021-09-01 12:00:00
```
说明在给定的工作时间段内,从 10:30 开始,90 分钟后的时间是 12:00。
阅读全文