JAVA 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.传入一个指定天(Date类型yyyy-MM-dd),该天已知在工作开始和结束日期之间 5.计算第四步这一天这台设备工作了多少分钟 单位(分钟)
时间: 2024-02-05 14:10:54 浏览: 108
以下是JAVA代码实现:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DeviceWorkTime {
private String workTimeStr; // 设备工作时段字符串
private Date workStartTime; // 设备工作开始日期时间
private Date workEndTime; // 设备工作结束日期时间
public DeviceWorkTime(String workTimeStr, Date workStartTime, Date workEndTime) {
this.workTimeStr = workTimeStr;
this.workStartTime = workStartTime;
this.workEndTime = workEndTime;
}
// 计算指定日期设备工作时长(单位:分钟)
public int calculateWorkingTime(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String targetDateStr = dateFormat.format(date);
String[] timeRanges = workTimeStr.split(";");
int totalWorkingTime = 0;
for (String timeRange : timeRanges) {
String[] startAndEndTime = timeRange.split("-");
String startTimeStr = targetDateStr + " " + startAndEndTime[0] + ":00";
String endTimeStr = targetDateStr + " " + startAndEndTime[1] + ":00";
try {
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTimeStr);
Date endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTimeStr);
// 如果开始时间在工作开始和结束时间之间,计算工作时长
if (startTime.after(workStartTime) && endTime.before(workEndTime)) {
int workingTime = (int) ((endTime.getTime() - startTime.getTime()) / (1000 * 60));
totalWorkingTime += workingTime;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return totalWorkingTime;
}
}
```
使用示例:
```java
public static void main(String[] args) throws Exception {
String workTimeStr = "09:00-12:00;13:00-18:00";
Date workStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2022-11-01 09:00:00");
Date workEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2022-11-05 18:00:00");
DeviceWorkTime deviceWorkTime = new DeviceWorkTime(workTimeStr, workStartTime, workEndTime);
Date targetDate = new SimpleDateFormat("yyyy-MM-dd").parse("2022-11-03");
int workingTime = deviceWorkTime.calculateWorkingTime(targetDate);
System.out.println("设备在" + targetDate + "工作了" + workingTime + "分钟");
}
```
阅读全文