手写好用工具类
1.BeanCopierUtils拷贝工具类
BeanCopier的拷贝比spring的BeanUtils效率高,
BeanUtils如果拷贝空字段还会出问题,需要处理空字段的拷贝
package xxx.utils;
import org.springframework.cglib.beans.BeanCopier;
public class BeanCopierUtils<T> {
//参数说明:s是源类型class,t是目标类的class,source是源对象
public static <T> T copy(Class s, Class t, Object source) {
T o = null;
try {
o = (T) t.newInstance();
BeanCopier beanCopier = BeanCopier.create(s, t, false);
beanCopier.copy(source, o, null);
} catch (Exception e) {
throw new RuntimeException("对象拷贝异常");
}
return o;
}
}
2.WrapperUtils工具类
该工具类是mybatisPlus使用每次查询的时候都要写很多重复的代码,所以写了下面这个工具类,可以大幅度降低一些重复的代码
package xxx.utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.IService;
import groovy.lang.Tuple2;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDateTime;
import java.util.Objects;
public class WrapperUtils {
public static <T> void startEndTimeCheckBuildLambdaQuery(LambdaQueryWrapper<T> lambda, String startTime, String endTime, SFunction<T, LocalDateTime> s, String customTimeField) {
if (StringUtils.isNotBlank(startTime)
&& StringUtils.isNotBlank(endTime)
&& !Objects.equals(startTime, endTime)) {
DateUtils.checkBothTimeStr(startTime, endTime, DateUtils.df1);
if (StringUtils.isNotBlank(customTimeField)) {
lambda.apply(customTimeField + " >= CAST('" + startTime + "' AS datetime) AND " + customTimeField + " <= CAST( '" + endTime + "' AS datetime)");
} else {
lambda.apply("create_time >= CAST('" + startTime + "' AS datetime) AND create_time <= CAST( '" + endTime + "' AS datetime)");
}
} else if (StringUtils.isNotBlank(startTime)
&& StringUtils.isNotBlank(endTime)
&& Objects.equals(startTime, endTime)) {
lambda.eq(s, startTime);
}
}
public static <T> QueryWrapper<T> buildQueryWrapper() {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
return queryWrapper;
}
public static <T> LambdaQueryWrapper<T> buildLambdaQueryWrapper(QueryWrapper<T> queryWrapper) {
LambdaQueryWrapper<T> lambda = queryWrapper.lambda();
return lambda;
}
public static <T> Tuple2<QueryWrapper<T>, LambdaQueryWrapper<T>> getWrapperLambda() {
QueryWrapper<T> queryWrapper = WrapperUtils.buildQueryWrapper();
LambdaQueryWrapper<T> lambda = WrapperUtils.buildLambdaQueryWrapper(queryWrapper);
return new Tuple2<>(queryWrapper, lambda);
}
public static <T> T getOneLast(IService<T> service, QueryWrapper<T> queryWrapper, LambdaQueryWrapper<T> lambda) {
lambda.last("limit 1");
return service.getOne(queryWrapper);
}
}
3.DateUtils工具类
该工具类之前也有分享过的,只不过后面我又在之前的基础上新写了几个方法
package xxxxx.utils;
import cn.hutool.core.collection.CollectionUtil;
import groovy.lang.Tuple2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Slf4j
public class DateUtils {
public static final DateTimeFormatter df1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter df2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static final DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
public static final DateTimeFormatter df4 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
public static final DateTimeFormatter df5 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
public static final String DAY = "DAY";
public static final String HOURS = "HOURS";
public static final String MINUTES = "MINUTES";
public static long timeSubstract(LocalDateTime startTime, LocalDateTime endTime, String returnType) {
if (StringUtils.equals(returnType, HOURS)) {
return Duration.between(startTime, endTime).toHours();
}
if (StringUtils.equals(returnType, DAY)) {
return Duration.between(startTime, endTime).toDays();
}
if (StringUtils.equals(returnType, MINUTES)) {
return Duration.between(startTime, endTime).toMinutes();
}
return 0L;
}
public static String localDateTimeToString(LocalDateTime localDateTime) {
String format = df1.format(localDateTime);
return format;
}
public static String localDateTimeToStringToYMD(LocalDateTime localDateTime) {
String format = df2.format(localDateTime);
return format;
}
public static LocalDateTime stringToLocalDateTime(String dateTimeStr) {
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeStr, df1);
return localDateTime;
}
public static LocalDateTime stringIncludeTStrToLocalDateTime(String dateTimeStr) {
log.info("stringIncludeTStrToLocalDateTime入参:{}", dateTimeStr);
dateTimeStr = dateTimeStr.replace("'T'", " ");
dateTimeStr = dateTimeStr.substring(0, 19);
log.info("stringIncludeTStrToLocalDateTime.dateTimeStr处理后的值:{}", dateTimeStr);
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeStr, df1);
return localDateTime;
}
public static LocalDateTime stringIncludeTStrToLocalDateTime2(String dateTimeStr) {
log.info("stringIncludeTStrToLocalDateTime入参:{}", dateTimeStr);
dateTimeStr = dateTimeStr.replace("T", " ");
dateTimeStr = dateTimeStr.substring(0, 19);
log.info("stringIncludeTStrToLocalDateTime.dateTimeStr处理后的值:{}", dateTimeStr);
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeStr, df1);
return localDateTime;
}
public static String localDateTimeToStringT(LocalDateTime localDateTime) {
String format = df3.format(localDateTime);
return format;
}
public static String localDateTimeToStringT2(LocalDateTime localDateTime) {
String format = df4.format(localDateTime).replace("T", " ");
return format;
}
public static String localDateTimeToStringT3(LocalDateTime localDateTime) {
String format = df5.format(localDateTime).replace("T", " ").replace("Z", " ");
format = format.substring(0, format.lastIndexOf("."));
return format;
}
public static LocalDateTime calculatTime(String time) {
LocalDateTime psTime = null;
if (org.apache.commons.lang3.StringUtils.isNotEmpty(time) && !(time.indexOf("-") != -1)) {
String s = time;
s = s.substring(0, 4) + "-" + s.substring(4, 6) + "-" + s.substring(6, 8) + " " + s.substring(8, 10) + ":" + s.substring(10, 12) + ":" + s.substring(12, 14);
psTime = DateUtils.stringToLocalDateTime(s);
} else if (org.apache.commons.lang3.StringUtils.isNotEmpty(time) && (time.indexOf("-") != -1)) {
String passTime = time;
if (passTime.contains("T")) {
psTime = DateUtils.stringIncludeTStrToLocalDateTime(passTime);
} else {
psTime = DateUtils.stringToLocalDateTime(passTime);
}
}
return psTime;
}
public static List<String> calculationDays(String startTime, String endTime) {
List<String> allDays = new ArrayList<>();
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDt = LocalDate.parse(startTime, dateTimeFormatter1);
int start_Y = startDt.getYear();
int start_M = startDt.getMonth().getValue();
int start_D = startDt.getDayOfMonth();
log.info("Y=" + start_Y + ",M=" + start_M + ",D=" + start_D);
LocalDate endDt = LocalDate.parse(endTime, dateTimeFormatter1);
int start_Y1 = endDt.getYear();
int start_M1 = endDt.getMonth().getValue();
int start_D1 = endDt.getDayOfMonth();
log.info("Y1=" + start_Y1 + ",M1=" + start_M1 + ",D1=" + start_D1);
if (startDt.compareTo(endDt) > 1) {
//开始时间大于结束时间返回空!
return null;
}
String endTimeStr = dateTimeFormatter1.format(endDt);
Period period = Period.between(LocalDate.parse(startTime), endDt);
StringBuffer sb = new StringBuffer();
sb.append(period.getYears()).append(",")
.append(period.getMonths()).append(",")
.append(period.getDays());
log.info("=======时间分量:=======" + sb.toString());
int py = start_Y1 - start_Y;
int Y = 12;
detailYear(allDays, start_Y, py, Y);
log.info("=======allDays--size()=======" + allDays.size());
if (CollectionUtil.isNotEmpty(allDays)) {
for (int i = 0; i < allDays.size(); i++) {
log.info(allDays.get(i) + "--------allDays------>第" + (i + 1) + "天");
}
List<String> okResult = getOkResult(allDays, startTime, endTimeStr);
System.out.println("=======okResult--size()=======" + okResult.size());
for (int i = 0; i < okResult.size(); i++) {
log.info(okResult.get(i) + "--------okResult-------->第" + (i + 1));
}
return okResult;
}
return null;
}
/**
* 处理整年
*
* @param allDays
* @param start_Y
* @param py
* @param y
*/
private static void detailYear(List<String> allDays, int start_Y, int py, int y) {
//处理年的天
for (int i = start_Y; i < start_Y + py + 1; i++) {
for (int j = 1; j <= y; j++) {
String fst = "";
if (j <= 9) {
fst = i + "-0" + j + "-01";
} else {
fst = i + "-" + j + "-01";
}
int diff_day = getDiff_day(fst);
for (int k = 1; k <= diff_day + 1; k++) {
String d = "";
if (j <= 9) {
d = i + "-0" + j;
if (k <= 9) {
d += "-0" + k;
} else if (k > 9) {
d += "-" + k;
}
} else if (j > 9) {
d = i + "-" + j;
if (k <= 9) {
d += "-0" + k;
} else if (k > 9) {
d += "-" + k;
}
}
allDays.add(d);
}
}
}
}
/**
* 获取正确的List
*
* @param startTime
* @param allDays
* @return
*/
private static List<String> getOkResult(List<String> allDays, String startTime, String endTime) {
List<String> result = new ArrayList<>();
int indexStart = 0;
int indexEnd = 0;
for (int i = 0; i < allDays.size(); i++) {
if (allDays.get(i).equals(startTime)) {
indexStart = i;
}
}
for (int i = 0; i < allDays.size(); i++) {
if (allDays.get(i).equals(endTime)) {
indexEnd = i;
}
}
result = allDays.subList(indexStart, indexEnd + 1);
return result;
}
/**
* 根据当月第一天计算本月的开始天和结束天
*
* @param fst
* @return
*/
private static int getDiff_day(String fst) {
LocalDate fstLd = LocalDate.parse(fst);
//获取月的第一天
LocalDate fstLd_fd = fstLd.with(TemporalAdjusters.firstDayOfMonth());
//获取月的最后一天
LocalDate fstLd_ld = fstLd.with(TemporalAdjusters.lastDayOfMonth());
Period period2 = Period.between(fstLd_fd, fstLd_ld);
int diff_day = period2.getDays();
return diff_day;
}
/**
* @param startTime
* @param endTime
*/
public static void checkBothTimeStr(String startTime, String endTime, DateTimeFormatter df) {
if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime) && Objects.nonNull(df)) {
LocalDateTime startDateTime = LocalDateTime.parse(startTime, df);
LocalDateTime endDateTime = LocalDateTime.parse(endTime, df);
//开始时间需要小于结束时间
if (startDateTime.compareTo(endDateTime) > 0) {
throw new RuntimeException("开始时间需小于结束时间!");
}
}
}
/**
* 计算前一个月的开始结束时间 monthsPlus传 -1
* 以此类推
*
* @param monthsPlus
* @return
*/
public static Tuple2<String, String> getMonthStartEnd(Long monthsPlus) {
LocalDateTime nowTime = LocalDateTime.now();
LocalDateTime plusMonthsFirstTime = null;
LocalDateTime plusMonthsLastTime = null;
if (Objects.nonNull(monthsPlus)) {
LocalDateTime beforeMonthCurrentTime = nowTime.plusMonths(monthsPlus);
plusMonthsFirstTime = beforeMonthCurrentTime.with(TemporalAdjusters.firstDayOfMonth());
plusMonthsLastTime = beforeMonthCurrentTime.with(TemporalAdjusters.lastDayOfMonth());
} else {
plusMonthsFirstTime = nowTime.with(TemporalAdjusters.firstDayOfMonth());
plusMonthsLastTime = nowTime.with(TemporalAdjusters.lastDayOfMonth());
}
String startStr = DateUtils.localDateTimeToString(plusMonthsFirstTime);
String endStr = DateUtils.localDateTimeToString(plusMonthsLastTime);
return new Tuple2<>(startStr, endStr);
}
public static Tuple2<String, String> getCurrentLocaleDateTimeStartEnd() {
LocalDateTime date = LocalDateTime.now();
// 获取一天的开始时间
LocalDateTime startOfTheDay = LocalDateTime.of(date.toLocalDate(), LocalTime.MIN);
// 获取一天的结束时间
LocalDateTime endOfTheDay = LocalDateTime.of(date.toLocalDate(), LocalTime.MAX);
String startStr = DateUtils.localDateTimeToString(startOfTheDay);
String endStr = DateUtils.localDateTimeToString(endOfTheDay);
log.info("getCurrentLocaleDateTimeStartEnd.startStr:{},endStr:{}", startStr, endStr);
return new Tuple2<>(startStr, endStr);
}
}
4.总结
上面都是一些我手写的经过长时间的项目经验代码的积累,可以减少重复的代码,写出优雅美观干净清秀工整的代码,所以干啥都需要厚积薄发,不断的去学习,去思考,去实践,去总结和沉淀,希望我的分享对你有所启发和帮助,请一键三连,么么么哒!