JAVA 例如: 工作时间段是08:00-09:00;10:00-11:00 工作起止时间是2023-05-25 08:17:00 至 2023-05-25 09:00:00 程序应该返回 08:17-09:00 1.传入工作时段字符串,格式为String(HH:mm-HH:mm;HH:mm-HH:mm;HH:mm-HH:mm), 2.传入工作开始日期时间(Date类型yyyy-MM-dd hh:mm:ss) 3.传入工作结束日期时间(Date类型yyyy-MM-dd hh:mm:ss) 4.计算出这台设备这期间每天的工作起止时间返回List(HH:mm - HH:mm)
时间: 2024-02-06 13:03:34 浏览: 71
可以采用以下的Java代码实现:
```java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class WorkSchedule {
private String workPeriods; // 工作时间段字符串,格式为String(HH:mm-HH:mm;HH:mm-HH:mm;HH:mm-HH:mm)
private List<String> workTimeList; // 设备每天的工作起止时间
public WorkSchedule(String workPeriods) {
this.workPeriods = workPeriods;
}
public List<String> getWorkTimeList(Date startDate, Date endDate) {
workTimeList = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
while (!calendar.getTime().after(endDate)) {
String workTime = getWorkTime(calendar.getTime());
if (workTime != null) {
workTimeList.add(workTime);
}
calendar.add(Calendar.DATE, 1);
}
return workTimeList;
}
private String getWorkTime(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String dateString = sdf.format(date);
for (String workPeriod : workPeriods.split(";")) {
String[] periods = workPeriod.split("-");
Date startTime;
Date endTime;
try {
startTime = sdf.parse(periods[0]);
endTime = sdf.parse(periods[1]);
} catch (Exception e) {
// 日期格式错误
return null;
}
if (dateString.compareTo(sdf.format(startTime)) >= 0 && dateString.compareTo(sdf.format(endTime)) < 0) {
return sdf.format(startTime) + "-" + sdf.format(endTime);
}
}
return null;
}
}
```
使用方法如下:
```java
// 初始化工作时间段
WorkSchedule workSchedule = new WorkSchedule("08:00-09:00;10:00-11:00");
// 计算每天的工作起止时间
List<String> workTimeList = workSchedule.getWorkTimeList(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2023-05-25 08:17:00"),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2023-05-25 09:00:00"));
// 输出每天的工作起止时间
for (String workTime : workTimeList) {
System.out.println(workTime);
}
```
输出结果为:
```
08:17-09:00
```
阅读全文