java 工具类日期工具类
1.DateTimeHelper.java
package cn.togeek.util; import cn.hutool.core.date.LocalDateTimeUtil; import cn.hutool.core.lang.Pair; import cn.hutool.core.util.NumberUtil; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import cn.togeek.enums.DateType; import java.nio.charset.Charset; import java.time.DayOfWeek; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DateTimeHelper { public static final String DATE_PATTERN = "yyyy-MM-dd"; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_PATTERN); public static final String DATE_STR_PATTERN = "yyyy年MM月dd日"; public static final DateTimeFormatter DATE_STR_FORMATTER = DateTimeFormatter.ofPattern(DATE_STR_PATTERN); public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(DATETIME_PATTERN); public static final String DATETIME_96_PATTERN = "MMdd HH:mm"; public static final DateTimeFormatter DATETIME_96_FORMATTER = DateTimeFormatter.ofPattern(DATETIME_96_PATTERN); public static final String TIME_HM_PATTERN = "HH:mm"; public static final DateTimeFormatter DATETIME_96_TIME_FORMATTER = DateTimeFormatter.ofPattern(TIME_HM_PATTERN); public static final DateTimeFormatter TIME_HM_FORMATTER = DateTimeFormatter.ofPattern(TIME_HM_PATTERN); public static final String DATE_96_PATTERN = "MMdd "; public static final DateTimeFormatter DATE_96_FORMATTER = DateTimeFormatter.ofPattern(DATE_96_PATTERN); public static final String MONTH_DAY_PATTERN = "MM月dd日 "; public static final DateTimeFormatter MONTH_DAY_FORMATTER = DateTimeFormatter.ofPattern(MONTH_DAY_PATTERN); public static final String END_TIME_STR = "24:00"; private static final Map<String, DateTimeFormatter> formatters = new HashMap<>(); static { formatters.put(DATE_PATTERN, DATE_FORMATTER); formatters.put(DATETIME_PATTERN, DATETIME_FORMATTER); } private DateTimeHelper() { } public static LocalDate date2LocalDate(Date date) { Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); return instant.atZone(zoneId).toLocalDate(); } public static LocalDateTime date2LocalDateTime(Date date) { Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); return instant.atZone(zoneId).toLocalDateTime(); } public static LocalDateTime text2LocalDateTime(String timeText) { return text2LocalDateTime(timeText, null); } public static LocalDateTime text2LocalDateTime(String timeText, String pattern) { pattern = pattern == null ? DATETIME_PATTERN : pattern; if(formatters.get(pattern) == null) { formatters.put(pattern, DateTimeFormatter.ofPattern(pattern)); } return LocalDateTime.parse(timeText, formatters.get(pattern)); } public static String localDateTime2Text(LocalDateTime dateTime) { return localDateTime2Text(dateTime, null); } public static String localDateTime2Text(LocalDateTime dateTime, String pattern) { pattern = pattern == null ? DATETIME_PATTERN : pattern; if(formatters.get(pattern) == null) { formatters.put(pattern, DateTimeFormatter.ofPattern(pattern)); } return formatters.get(pattern).format(dateTime); } public static LocalDate text2LocalDate(String dateText) { return text2LocalDate(dateText, null); } public static LocalDate text2LocalDate(String timeText, String pattern) { pattern = pattern == null ? DATE_PATTERN : pattern; if(formatters.get(pattern) == null) { formatters.put(pattern, DateTimeFormatter.ofPattern(pattern)); } return LocalDate.parse(timeText, formatters.get(pattern)); } public static String localDate2Text(LocalDate date) { return localDate2Text(date, null); } public static String localDate2Text(LocalDate date, String pattern) { pattern = pattern == null ? DATE_PATTERN : pattern; if(formatters.get(pattern) == null) { formatters.put(pattern, DateTimeFormatter.ofPattern(pattern)); } return formatters.get(pattern).format(date); } public static Date localDate2Date(LocalDate localDate) { ZoneId zone = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = localDate.atStartOfDay(zone); return Date.from(zonedDateTime.toInstant()); } public static Date localDateTime2Date(LocalDateTime localDateTime) { ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); return Date.from(instant); } public static long localDateTime2Timestamp(LocalDateTime localDateTime) { ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); return instant.toEpochMilli(); } public static LocalDateTime timestamp2LocalDateTime(long timestamp) { Instant instant = Instant.ofEpochMilli(timestamp); ZoneId zone = ZoneId.systemDefault(); return LocalDateTime.ofInstant(instant, zone); } public static LocalDateTime beginOfDay(LocalDateTime localDateTime) { return localDateTime.with(LocalTime.MIN); } public static LocalDateTime beginOfDay(LocalDate localDate) { return LocalDateTime.of(localDate, LocalTime.MIN); } public static LocalDateTime endOfDay(LocalDateTime localDateTime) { return localDateTime.with(LocalTime.MAX); } public static LocalDateTime endOfDay(LocalDate localDate) { return LocalDateTime.of(localDate, LocalTime.MAX); } public static LocalDateTime beginOfMonth(LocalDateTime localDateTime) { return localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalDateTime.MIN); } public static LocalDateTime beginOfMonth(LocalDate localDate) { return LocalDateTime.of(localDate.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN); } public static LocalDateTime endOfMonth(LocalDateTime localDateTime) { return localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalDateTime.MAX); } public static LocalDateTime endOfMonth(LocalDate localDate) { return LocalDateTime.of(localDate.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX); } public static LocalDateTime beginOfYear(LocalDateTime localDateTime) { return localDateTime.with(TemporalAdjusters.firstDayOfYear()).with(LocalDateTime.MIN); } public static LocalDateTime beginOfYear(LocalDate localDate) { return LocalDateTime.of(localDate.with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN); } public static LocalDateTime endOfYear(LocalDateTime localDateTime) { return localDateTime.with(TemporalAdjusters.lastDayOfYear()).with(LocalDateTime.MAX); } public static LocalDateTime endOfYear(LocalDate localDate) { return LocalDateTime.of(localDate.with(TemporalAdjusters.lastDayOfYear()), LocalTime.MAX); } public static LocalDate firstDayOfMonth(LocalDate localDate) { return localDate.with(TemporalAdjusters.firstDayOfMonth()); } public static LocalDate lastDayOfMonth(LocalDate localDate) { return localDate.with(TemporalAdjusters.lastDayOfMonth()); } public static LocalDate firstDayOfYear(LocalDate localDate) { return localDate.with(TemporalAdjusters.firstDayOfYear()); } public static LocalDate lastDayOfYear(LocalDate localDate) { return localDate.with(TemporalAdjusters.lastDayOfYear()); } public static List<LocalDate> getDateList(LocalDate beginDate, LocalDate endDate) { long range = ChronoUnit.DAYS.between(beginDate, endDate) + 1; List<LocalDate> list = new ArrayList<>(); for (long i = 0; i < range; i++) { list.add(beginDate.plusDays(i)); } return list; } /** * 根据年月字符串获取当月第一天和最后一天 */ public static Map<String, LocalDate> getDateByYmstr(String date) { String str = date + "-01"; LocalDate firstDay = LocalDate.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate lastDate = firstDay.with(TemporalAdjusters.lastDayOfMonth()); Map<String, LocalDate> map = new HashMap<>(); map.put("firstDay", firstDay); map.put("lastDate", lastDate); return map; } /** * 获取前一天日期 */ public static String yesterday() { // 获取当前日期 LocalDate today = LocalDate.now(); // 获取当前日期的前一天 return today.minusDays(1).toString(); } /** * 获取后一天日期 */ public static String tomorrow() { // 获取当前日期 LocalDate today = LocalDate.now(); // 获取当前日期的前一天 return today.plusDays(1).toString(); } public static LocalDateTime strToDateTime(String dateStr, String timeStr) { return LocalDateTime.of(LocalDate.parse(dateStr), LocalTime.parse(timeStr)); } public static String numberToTimeStr(int i) { return String.format("%02d:%02d", i * 15 / 60, i * 15 % 60); } public static int timeStrToNumber(String timeStr) { String[] split = timeStr.split(":"); return NumberUtil.toBigInteger(split[0]).intValue() * 4 + NumberUtil.toBigInteger(split[1]).intValue() / 15; } public static LocalTime numberToLocalTime(int i) { try { return LocalTime.of(i*15/60, i*15%60); } catch(Exception e){ return LocalTime.MIN; } } public static synchronized String fixTime(String timeStr, boolean hasSecond) { if (!timeStr.contains(":")) { throw new IllegalArgumentException("时间格式有误"); } if (timeStr.contains(" ")) { timeStr = timeStr.split(" ")[1]; } List<String> split = Arrays.stream(timeStr.split(":")).collect(Collectors.toList()); if (!hasSecond && split.size() == 3) { split.remove(2); } StringBuffer time = new StringBuffer(); for (int i = 0; i < split.size(); i++) { String str = split.get(i); String it; if(str.length() < 2) { it = "0" + str; } else { it = str; } time.append(it); if(i != split.size() - 1) { time.append(":"); } } return time.toString(); } public static String fixDate(String bsStr) { String[] fixed; String sepPoint = "."; boolean point = bsStr.contains(sepPoint); if (point) { fixed = bsStr.split("\\."); } else { fixed = bsStr.split("-"); } String sep = point ? sepPoint : "-"; return String.format("%s%s%02d%s%02d", fixed[0], sep, Integer.parseInt(fixed[1]), sep, Integer.parseInt(fixed[2])); } public static List<String> genarateTime(boolean has2400) { if (has2400) { return IntStream.rangeClosed(1, 96).mapToObj(i -> numberToTimeStr(i)).collect(Collectors.toList()); } else { return IntStream.rangeClosed(0, 95).mapToObj(i -> numberToTimeStr(i)).collect(Collectors.toList()); } } /*** * 00:15-24:00 * @param start * @param end * @param format * @return * @param <T> */ public static <T> List<T> getDateList96(LocalDate start, LocalDate end, Function<LocalDateTime, T> format) { List<T> list = Lists.newArrayList(); LocalDate item = start; while (item.isBefore(end) || item.isEqual(end)) { LocalTime time = LocalTime.MIN; for (int i = 0; i < 96; i++) { time = time.plusMinutes(15l); list.add(format.apply(LocalDateTime.of(item, time))); } item = item.plusDays(1l); } return list; } public static void main(String[] args) { List<LocalDateTime> dateList96 = DateTimeHelper.getDateList96(LocalDate.now(), LocalDate.now(), Function.identity()); System.out.println(dateList96); } public static List<String> getDateList96(LocalDate start, LocalDate end) { return getDateList96(start, end, DEFAULT_DATE_96_FUNC); } public static final Function<LocalDateTime, String> DEFAULT_DATE_96_FUNC = e -> e.toLocalTime().equals(LocalTime.MIN) ? DATE_96_FORMATTER.format(e).concat(END_TIME_STR) : DATETIME_96_FORMATTER.format(e); public static List<String> getDateList96Time(LocalDate start, LocalDate end) { List<String> dateList96Time = getDateList96(start, end, DEFAULT_DATE_FUNC); return dateList96Time.stream().map(l -> { if ("00:00".equals(l)) { l = "24:00"; } return l; }).collect(Collectors.toList()); } public static final Function<LocalDateTime, String> DEFAULT_DATE_FUNC = e -> DATETIME_96_TIME_FORMATTER.format(e); public static List<String> getBetweenToTime(String startTime, String endTime) { int start = timeStrToNumber(startTime); int end = timeStrToNumber(endTime); return IntStream.range(start, end + 1).mapToObj(DateTimeHelper::numberToTimeStr).collect(Collectors.toList()); } public static LocalDate parseLocalDate(Object date) { String[] parttens = { "yyyy-MM-dd", "yyyy-M-dd", "yyyy-M-d", "yyyy.MM.dd", "yyyy.M.dd", "yyyy.M.d", "yyyy年MM月dd日", "yyyy年M月dd日", "yyyy年M月d日", "yyyy/MM/dd", "yyyy/M/dd", "yyyy/M/d", "yyyyMMdd", "yyyyMdd", "yyyyMd", }; if(date == null) { return null; } if(date instanceof Date) { return LocalDateTimeUtil.of(((Date) date)).toLocalDate(); } else if (date instanceof String) { String dateStr = (String) date; for(String partten : parttens) { try { return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(partten)); } catch(Exception e) { } } } return null; } public static boolean isBetween(LocalDate start, LocalDate end, LocalDate... dates) { boolean ok = true; for(LocalDate date : dates) { ok &= !date.isBefore(start) && !date.isAfter(end); } return ok; } public static List<String> getPoint96(){ return IntStream.rangeClosed(1, 96).mapToObj(DateTimeHelper::numberToTimeStr).collect(Collectors.toList()); } /** * 获取指定开始结束日期内的日期类型 * @param begin * @param end * @return */ public static Map<DateType,List<LocalDate>> getSortedDays(LocalDate begin, LocalDate end){ Map<DateType,List<LocalDate>> dateTypeListMap = new LinkedHashMap<>(); List<LocalDate> visited = new ArrayList<>(); IntStream.rangeClosed(begin.getYear(), end.getYear()).forEach(year->{ String url = "http://timor.tech/api/holiday/year/"+year; String result = HttpUtil.get(url, Charset.forName("UTF-8")); JSONObject info = JSONObject.parseObject(result); JSONObject holiday = info.getJSONObject("holiday"); for(String dateStr : holiday.keySet()) { String fullDate = year+"-"+dateStr; JSONObject dateInfo = holiday.getJSONObject(dateStr); Boolean isHoliday = dateInfo.getBoolean("holiday"); DateType dateType = isHoliday ? DateType.HOLIDAY : DateType.ADJUSTHOLIDAY; dateTypeListMap.computeIfAbsent(dateType,(s)-> new ArrayList<>()); LocalDate date = LocalDate.parse(fullDate); visited.add(date); dateTypeListMap.get(dateType).add(date); } }); while(!begin.isAfter(end)) { if(!visited.contains(begin)) { DayOfWeek dayOfWeek = begin.getDayOfWeek(); DateType dateType; switch(dayOfWeek) { case SATURDAY: dateType = DateType.SATURDAY; break ; case SUNDAY: dateType = DateType.SUNDAY; break ; default: dateType = DateType.WORKINGDAY; break; } dateTypeListMap.computeIfAbsent(dateType,(s)-> new ArrayList<>()); dateTypeListMap.get(dateType).add(begin); } begin = begin.plusDays(1); } return dateTypeListMap; } /** * 获取指定开始结束日期内的日期类型 * @param begin * @param end * @return */ public static Map<LocalDate,DateType> getDaysType(LocalDate begin, LocalDate end){ Map<LocalDate,DateType> dateTypeListMap = new LinkedHashMap<>(); IntStream.rangeClosed(begin.getYear(), end.getYear()).forEach(year->{ String url = "http://timor.tech/api/holiday/year/"+year; String result = HttpUtil.get(url, Charset.forName("UTF-8")); JSONObject info = JSONObject.parseObject(result); JSONObject holiday = info.getJSONObject("holiday"); for(String dateStr : holiday.keySet()) { String fullDate = year+"-"+dateStr; LocalDate date = LocalDate.parse(fullDate); if(DateTimeHelper.isBetween(begin,end,date)) { JSONObject dateInfo = holiday.getJSONObject(dateStr); Boolean isHoliday = dateInfo.getBoolean("holiday"); DateType dateType = isHoliday ? DateType.HOLIDAY : DateType.ADJUSTHOLIDAY; dateTypeListMap.put(date,dateType); } } }); LocalDate cur = LocalDate.from(begin); while(!cur.isAfter(end)) { if(!dateTypeListMap.keySet().contains(cur)) { DayOfWeek dayOfWeek = cur.getDayOfWeek(); DateType dateType; switch(dayOfWeek) { case SATURDAY: dateType = DateType.SATURDAY; break ; case SUNDAY: dateType = DateType.SUNDAY; break ; default: dateType = DateType.WORKINGDAY; break; } dateTypeListMap.put(cur,dateType); } cur = cur.plusDays(1); } return dateTypeListMap; } /** * 给定开始结束日期,给定一个月份,求这个月在给定开始结束时间内的开始结束时间 * @param begin * @param end * @param month * @return */ public static Pair<LocalDate,LocalDate> getBeginAndEnd(LocalDate begin, LocalDate end, int month){ LocalDate cur = LocalDate.from(begin); LocalDate start = null,ends = null; while(!cur.isAfter(end)) { if(cur.getMonthValue() < month) { cur = cur.plusMonths(1); continue; } if(cur.getMonthValue() > month) { break; } if(start == null) { start = cur; } cur = cur.plusDays(1); } ends = cur; return Pair.of(start,ends.getMonthValue() == month?ends:ends.minusDays(1)); } /** * 根据月份获取该月每周的日期列表 * @param yearMonth * @return */ public static Map<Integer,List<LocalDate>> getWeekMap(YearMonth yearMonth){ YearMonth month = YearMonth.from(yearMonth); LocalDate start = LocalDate.of(month.getYear(),month.getMonth(),1); int dayOfMonth = month.lengthOfMonth(); LocalDate end = LocalDate.of(month.getYear(),month.getMonth(), dayOfMonth); Map<Integer,List<LocalDate>> map = new LinkedHashMap<>(); int week = 1; boolean willPlus = false; while(!start.isAfter(end)) { List<LocalDate> dateList = map.computeIfAbsent(week, (w)->Lists.newArrayList()); dateList.add(start); if(willPlus) { willPlus = false; week++; } start = start.plusDays(1); if(start.getDayOfWeek().getValue() == 7) { willPlus = true; } } return map; } }
2.DateType.java
package cn.togeek.enums; /** * 日期类型:周六,周日,工作日,法定节假日,调休节假日 */ public enum DateType { SATURDAY("周六"), SUNDAY("周日"), WORKINGDAY("工作日"), HOLIDAY("节假日"), ADJUSTHOLIDAY("调休节假日"); DateType(String typeName) { this.typeName = typeName; } private String typeName; public String getTypeName() { return typeName; } public static DateType getDataTypeByName(String typeName) { for(DateType dateType : DateType.values()) { if(dateType.getTypeName().equals(typeName)) { return dateType; } } return null; }
public static Map<Integer,List<LocalDate>> getWeekMap(YearMonth yearMonth){
YearMonth month = YearMonth.from(yearMonth);
LocalDate start = LocalDate.of(month.getYear(),month.getMonth(),1);
int dayOfMonth = month.lengthOfMonth();
LocalDate end = LocalDate.of(month.getYear(),month.getMonth(), dayOfMonth);
Map<Integer,List<LocalDate>> map = new LinkedHashMap<>();
int week = 1;
boolean willPlus = false;
while(!start.isAfter(end)) {
List<LocalDate> dateList = map.computeIfAbsent(week, (w)->Lists.newArrayList());
dateList.add(start);
if(willPlus) {
willPlus = false;
week++;
}
start = start.plusDays(1);
if(start.getDayOfWeek().getValue() == 7) {
willPlus = true;
}
}
return map;
}
}
3.BeanUtils.java
package cn.togeek.util; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Pair; import cn.hutool.core.util.ReflectUtil; import cn.hutool.poi.excel.ExcelReader; import cn.hutool.poi.excel.ExcelUtil; import io.swagger.annotations.ApiModelProperty; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; @Slf4j public class BeanUtils { private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class); /** * map 对象转对象 * @param origion * @param t * @param <T> */ public static<T> void mapToBean(Map<String,Object> origion,T t){ Class<?> aClass = t.getClass(); Map<String, Field> mapping = new LinkedHashMap<>(); while(aClass != Object.class) { Map<String, Field> cur = Arrays.stream(aClass.getDeclaredFields()) .map(field -> Pair.of(field.getName().replaceAll("_", "").toLowerCase(), field)) .collect(Collectors.toMap(o -> o.getKey(), o -> o.getValue())); mapping.putAll(cur); aClass = aClass.getSuperclass(); } for(Map.Entry<String, Object> entry : origion.entrySet()) { String field = entry.getKey(); Object value = entry.getValue(); if(ReflectUtil.hasField(aClass, field) && ReflectUtil.getField(aClass,field).getType().equals(value.getClass())) { ReflectUtil.setFieldValue(t,field, value); } else { String field2 = field.replaceAll("_", "").toLowerCase(); if(mapping.containsKey(field2) && mapping.get(field2).getType().equals(value.getClass())) { ReflectUtil.setFieldValue(t,mapping.get(field2), value); continue; } logger.warn("origion map key:{} not in Class:{}",field,aClass); } } } /** * 获取指定类的注解信息与字段映射关系 * @param clazz * @return */ public static Map<String,Field> getApiModleInfoMap(Class clazz) { return Arrays.stream(ReflectUtil.getFields(clazz)) .filter(f->f.isAnnotationPresent(ApiModelProperty.class)).collect(Collectors.toMap(f->{ ApiModelProperty annotation = f.getAnnotation(ApiModelProperty.class); return annotation.value(); },f->f,(o1,o2)->o2)); } /** * 文件导入时使用 * @param clazz * @param errorInfo * @return */ public static <T> List<T> getBeanListFromListMap(Class<T> clazz, MultipartFile file, List<String> errorInfo) throws Exception { ExcelReader reader = ExcelUtil.getReader(file.getInputStream()); List<Map<String,Object>> xlsDataList = reader.readAll(); Map<String, Field> infoMap = getApiModleInfoMap(clazz); ArrayList<T> list = new ArrayList<>(); xlsDataList.forEach(map -> { try { T bean = clazz.newInstance(); list.add(bean); map.forEach((key,value) -> { Field field = infoMap.get(key); if(Objects.isNull(field)) { log.warn(String.format("key:%s not match any class field,it will be ignored,please check!!!",key)); } else { Class<?> type = field.getType(); if(Objects.isNull(value) || value.getClass() == type) { ReflectUtil.setFieldValue(bean,field,value); } else { Object convert = Convert.convert(type, value); ReflectUtil.setFieldValue(bean,field,convert); } } }); } catch(Exception e) { errorInfo.add(e.getMessage()); e.printStackTrace(); } }); return list; } }
4.多个list合并成一个list
package cn.togeek.util; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.ReflectUtil; import com.alibaba.fastjson.JSON; import com.google.common.collect.Maps; import lombok.AllArgsConstructor; import lombok.Data; import cn.togeek.exception.ClientError; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class DateTimeValueUtilPlus { public static final String QUART = "QUART"; public static final String HOUR = "HOUR"; // public static final String DAY = "DAY"; public static <T> List<T> genarate(LocalDate start, LocalDate end, String unit, Builder builder,Class<T> targetClazz){ List<T> result = new ArrayList<>(); for(LocalDate s= LocalDate.from(start);!s.isAfter(end);s=s.plusDays(1)) { switch(unit) { case QUART: case HOUR: int i = 0; for(LocalTime b=LocalTime.MIN;unit.equals(QUART)?i<96:i<24;b=b.plusMinutes(unit.equals(QUART)?15:60)) { T t = ReflectUtil.newInstanceIfPossible(targetClazz); ReflectUtil.setFieldValue(t,builder.dateField,s); ReflectUtil.setFieldValue(t,builder.timeField,b); for(Object[] datum : builder.data) { Class curClass = (Class) datum[0]; List<Part> parts = (List<Part>) datum[1]; Map<LocalDate,Map<LocalTime,Object>> curOrigionDataMap = (Map<LocalDate,Map<LocalTime,Object>>)datum[2]; for(Part part : parts) { String targetField = part.getTargetFieldName(); Function function = part.getOperation(); if(ReflectUtil.hasField(targetClazz,targetField)) { Object orDefault = curOrigionDataMap.getOrDefault(s, Maps.newHashMap()) .getOrDefault(b, ReflectUtil.newInstanceIfPossible(curClass)); Object o = function.apply(orDefault); ReflectUtil.setFieldValue(t,targetField,o); } } } i++; result.add(t); } break; default: throw new ClientError("非法参数"); } } return result; } public static class Builder{ List<Object[]> data = new ArrayList<>(); int index; String dateField; String timeField; /** * * @param dateField 目标类 日期字段名 * @param timeField 目标类 时刻字段名 * order = 0 * @return */ public static Builder of(String dateField, String timeField){ Builder builder = new Builder(); builder.dateField = dateField; builder.timeField = timeField; return builder; } /** * * @param origionListType 原始类class * order = 1 * @return */ public Builder origionClass(Class origionListType) { Object[] element = new Object[4]; element[0] = origionListType; data.add(index, element); return this; } /** * * @param parts 目标类字段名 * order = 2 * @return */ public Builder with(List<Part> parts) { data.get(index)[1] = parts; return this; } /** * order = 3 * @param originDateTimeInstanceMap 原始list 按日期时刻分类后的class * @return */ public Builder use(Map<LocalDate,Map<LocalTime,Object>> originDateTimeInstanceMap) { data.get(index)[2] = originDateTimeInstanceMap; return this; } } @Data @AllArgsConstructor public static class Part{ //目标类字段名 private String targetFieldName; //function 找到原始instance 后的取值逻辑 private Function operation; } public static void main(String[] args) { LocalDate start = LocalDate.parse("2023-08-01"); LocalDate end = LocalDate.parse("2023-08-04"); List<Power> powerList = DateTimeHelper.getDateList(start, end) .stream() .map(x -> DateTimeHelper.genarateTime(false).stream().map(t -> { Power power = new Power(); power.setPowerLong(RandomUtil.randomBigDecimal()); power.setPowerSpot(RandomUtil.randomBigDecimal()); power.setTime(LocalTime.parse(t)); power.setInfoDate(x); return power; }).collect(Collectors.toList())) .flatMap(Collection::stream) .collect(Collectors.toList()); List<Price> priceList = DateTimeHelper.getDateList(LocalDate.parse("2023-08-03"), end) .stream() .map(x -> DateTimeHelper.genarateTime(false).stream().map(t -> { Price power = new Price(); power.setPrice(RandomUtil.randomBigDecimal()); power.setTime(LocalTime.parse(t)); power.setBusinessDate(x); return power; }).collect(Collectors.toList())) .flatMap(Collection::stream) .collect(Collectors.toList()); Map<LocalDate,Map<LocalTime,Object>> collectPrice = priceList.stream() .collect(Collectors.groupingBy(Price::getBusinessDate, Collectors.toMap(Price::getTime, Function.identity()))); Map<LocalDate,Map<LocalTime,Object>> collectPower = powerList.stream() .collect(Collectors.groupingBy(Power::getInfoDate, Collectors.toMap(Power::getTime, Function.identity()))); List<PricePower> genarate = DateTimeValueUtilPlus.genarate(start, end, DateTimeValueUtilPlus.QUART, Builder.of("infoDate", "time") .origionClass(Price.class) .with(Arrays.asList(new Part("price",(p) -> ((Price) p).price ))) .use(collectPrice) .origionClass(Power.class) .with(Arrays.asList( new Part("powerSpot",(p) -> ((Power) p).powerSpot), new Part("powerLong",(p) -> ((Power) p).powerLong) )) .use(collectPower), PricePower.class); System.out.println(JSON.toJSONString(genarate)); } @Data static class Power{ LocalDate infoDate; LocalTime time; BigDecimal powerSpot; BigDecimal powerLong; } @Data static class Price{ LocalDate businessDate; LocalTime time; BigDecimal price; } @Data static class PricePower{ LocalDate infoDate; LocalTime time; BigDecimal price; BigDecimal powerSpot; BigDecimal powerLong; } }