最近公司做了一个工作流业务系统,需要统计每个节点人员处理的工时,方便对人员进行责任判定
需求是这样的,需要扣除非工作时长,这里就包含的有点多,比如上班之前,上班之后,午休时间,周六周日,法定节假日等等,这里简单记录一下代码,有需要的有缘人可以借鉴
我的实现方式是获取传入的时间段之间有多少天,每天呢时长其实是固定的,在计算出不满一天的时长是多少最后进行归总,结果进行了保留一位小数,这里需要说明一点如果处理时长不满6分钟会出现0.0的情况,如果存在跨年份也会出现只去除当前年的节假日的现象,个人进行了测试吧能想到的一些问题都做了处理,目前还没有提到测试进行测试有问题可以联系我会修复
package com.ctsi.ssdc.util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.lang.reflect.Type;
import java.math.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author dong
* @create 2024/8/23
* @describe 工时计算
*/
public class WorkHoursUtils {
static LocalTime restBeginsStart = LocalTime.of(11, 30);
static LocalTime restBeginsStop = LocalTime.of(13, 30);
static LocalTime goToWork = LocalTime.of(8, 30);
static LocalTime goOffWork = LocalTime.of(17, 30);
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static Map<String, List<String>> offDayMap;
static {
String year = getYear();
offDayMap = new HashMap<>();
offDayMap.put(year,getOffDay(year));
}
public static String getDuration(Object start, Object end) {
LocalDateTime startDate = dateConversion(start);
LocalDateTime endDate = dateConversion(end);
LocalTime time = LocalTime.MIDNIGHT;
List<LocalDateTime> list = generateDateRange(startDate.toLocalDate(), endDate.toLocalDate())
.stream()
.map(date -> LocalDateTime.of(date, time))
.collect(Collectors.toList());
BigDecimal result = BigDecimal.ZERO;
long decimalDuration = 0;
int germ = 1;
int offset = list.size() - 1;
int sum = 0;
List<String> offDay = getOffDayList();
if (list.size() == 1) {
// 如果为节假日直接返回0不计算工时
if (offDay.contains(startDate.toLocalDate().toString())) {
return result.toString();
}
//说明是当天提交当天完成的任务
decimalDuration = getIntraDayDuration(startDate.toLocalTime(), endDate.toLocalTime());
} else {
list.set(0, startDate);
list.set(offset, endDate);
//隔天完成的任务,计算时长
if (!offDay.contains(list.get(0).toLocalDate().toString())) {
decimalDuration += getIntraDayDuration(list.get(0).toLocalTime(), goOffWork);
}
if (!offDay.contains(list.get(offset).toLocalDate().toString())) {
decimalDuration += getIntraDayDuration(goToWork, list.get(offset).toLocalTime());
}
for (int i = germ; i < offset; i++) {
if (!offDay.contains(list.get(i).toLocalDate().toString())) {
sum += 1;
}
}
decimalDuration += sum * getEveryDayWorkHours();
}
result = new BigDecimal(decimalDuration).divide(new BigDecimal(60), 1, RoundingMode.HALF_UP);
return result.toString();
}
private static List<String> getOffDayList() {
String year = getYear();
List<String> offDay = offDayMap.get(year);
if (offDay.isEmpty()) {
offDayMap.put(year,getOffDay(year));
offDay = offDayMap.get(year);
}
return offDay;
}
private static LocalDateTime dateConversion(Object date) {
LocalDateTime startDate;
if (date instanceof String){
startDate = LocalDateTime.parse((String) date, formatter);
} else if (date instanceof Date){
startDate = LocalDateTime.parse(sdf.format(date), formatter);
} else{
startDate = (LocalDateTime) date;
}
return startDate;
}
private static long getEveryDayWorkHours() {
return Math.abs(ChronoUnit.MINUTES.between(goToWork, goOffWork)) -
Math.abs(ChronoUnit.MINUTES.between(restBeginsStart, restBeginsStop));
}
private static long getIntraDayDuration(LocalTime startTime, LocalTime stopTime) {
long minutesBetween = 0;
if (stopTime.isBefore(goToWork) || stopTime == goToWork || startTime.isAfter(goOffWork) || startTime == goOffWork) {
return minutesBetween;
}
//提交和结束的时间相差分钟数
minutesBetween = Math.abs(ChronoUnit.MINUTES.between(startTime, stopTime));
if (stopTime.isBefore(restBeginsStart)) {
return minutesBetween;
}
//如果在上班之前创建 减去上班之前到上班的时间分钟数
if (startTime.isBefore(goToWork) || startTime == goToWork) {
//在上午上班之前创建的工单,需要减去当前时间到8.30之间的分钟数
minutesBetween -= Math.abs(ChronoUnit.MINUTES.between(startTime, goToWork));
}
//午休时间创建的, 减去午休时间到下午上班13.30的分钟数
if ((startTime.isBefore(restBeginsStop) || startTime == restBeginsStop) && (startTime.isAfter(restBeginsStart) || startTime == restBeginsStop)) {
minutesBetween -= Math.abs(ChronoUnit.MINUTES.between(startTime, restBeginsStart));
}
//午休时间完成的 间去11.30 - 》当前时间之间的分钟数
if ((stopTime.isBefore(restBeginsStop) || stopTime == restBeginsStop) && (stopTime.isAfter(restBeginsStart) || startTime == restBeginsStart)) {
minutesBetween -= Math.abs(ChronoUnit.MINUTES.between(restBeginsStart, stopTime));
}
//下班后完成的减去下班到结束时间之间的时间
if (stopTime.isAfter(goOffWork) || stopTime == goOffWork) {
minutesBetween -= Math.abs(ChronoUnit.MINUTES.between(goOffWork, stopTime));
}
//午休之前创建的午休之后完成的
if (startTime.isBefore(restBeginsStart) && stopTime.isAfter(restBeginsStop)) {
minutesBetween -= Math.abs(ChronoUnit.MINUTES.between(restBeginsStart, restBeginsStop));
}
return minutesBetween;
}
public static List<LocalDate> generateDateRange(LocalDate startDate, LocalDate endDate) {
List<LocalDate> dateList = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dateList.add(startDate);
startDate = startDate.plusDays(1);
}
return dateList;
}
public static void main(String[] args) {
String duration = getDuration("2024-08-10 06:20:12", "2024-08-18 09:30:00");
System.out.println("duration = " + duration);
}
public static String getYear(){
// 获取当前日期
return String.valueOf(LocalDate.now().getYear());
}
private static List<String> getOffDay(String year) {
HashMap<String, List<String>> dayMap = getDayMap(year);
List<String> goToDayList = dayMap.get("goToDayList");
List<String> offDayList = dayMap.get("offDayList");
Set<String> weekendsOffDay = getWeekendsOffDay(year);
List<String> collect = weekendsOffDay.stream()
.filter(item -> !goToDayList.contains(item))
.collect(Collectors.toList());
offDayList.addAll(collect);
return offDayList;
}
private static HashMap<String, List<String>> getDayMap(String year) {
//法定节假日
String urlString = "https://api.jiejiariapi.com/v1/holidays/" + year;
Map<String, Map<String, Object>> map = executeHttp(urlString);
List<String> offDayList = new ArrayList<>();
List<String> goToDayList = new ArrayList<>();
for (String key : map.keySet()) {
boolean isOffDay = (boolean) map.get(key).get("isOffDay");
if (isOffDay) {
offDayList.add(key);
} else {
goToDayList.add(key);
}
}
HashMap<String, List<String>> hashMap = new HashMap<>();
hashMap.put("offDayList", offDayList);
hashMap.put("goToDayList", goToDayList);
return hashMap;
}
private static Set<String> getWeekendsOffDay(String year) {
String url = "https://api.jiejiariapi.com/v1/weekends/" + year;
Map<String, Map<String, Object>> map = executeHttp(url);
return map.keySet();
}
private static Map<String, Map<String, Object>> executeHttp(String url) {
Map<String, Map<String, Object>> map = new HashMap<>();
//周六周日
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
String responseBody = httpClient.execute(request, httpResponse ->
EntityUtils.toString(httpResponse.getEntity()));
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Map<String, Object>>>() {}.getType();
map = gson.fromJson(responseBody, type);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}