一.有关时间
1.时间配置
如果不配置的话返给前端的时间会少8个小时,格式也相当于乱码状态,解决方案:要么设置时区和格式;要么转成字符串传给前端
1.springboot全局日期设置
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
2. 字段上设置
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") // 设置出参的时区和格式(返给前端的参数)
@DateTimeFormat(pattern="yyyy-MM-dd")// 设置入参的格式(前端带过来的参数)
private Date createdDate;
2.工具类
1.计算两日期之间的天数
/**
*
* 计算两个日期之间相差的天数
* @param smdate 较小的时间
* @param bdate 较大的时间
* @return 相差天数
* @throws ParseException
*
*/
public static int daysBetween(Date smdate, Date bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
smdate = sdf.parse(sdf.format(smdate));
bdate = sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
2.计算工作时长h(固定上下班时间,固定午休时间,除去周六周日)
// 上班时间 8:00 private static final LocalTime WORKING_START_TIME = LocalTime.of(8, 0); // 下班时间 17:00 private static final LocalTime WORKING_END_TIME = LocalTime.of(17, 0); // 午休开始时间 12:00 private static final LocalTime NOON_BREAK_START_TIME = LocalTime.of(12, 0); // 午休结束时间 13:00 private static final LocalTime NOON_BREAK_END_TIME = LocalTime.of(13, 0);/** * 计算工作时长(固定上下班时间、固定午休时间,除去周六周日) * @param startDate * @param endDate * @return */ public static int getWorkTime(LocalDateTime startDateTime, LocalDateTime endDateTime) { if (startDateTime.compareTo(endDateTime) > 0) { throw new RuntimeException("参数错误"); } int diff = 0; while (true) { // TODO: 调休日期处理 // 跳过周六周日 if (startDateTime.getDayOfWeek() == DayOfWeek.SATURDAY) { startDateTime = LocalDateTime.of(startDateTime.toLocalDate(), WORKING_START_TIME).plusDays(2); } if (startDateTime.getDayOfWeek() == DayOfWeek.SUNDAY) { startDateTime = LocalDateTime.of(startDateTime.toLocalDate(), WORKING_START_TIME).plusDays(1); } if (endDateTime.getDayOfWeek() == DayOfWeek.SATURDAY) { endDateTime = LocalDateTime.of(endDateTime.toLocalDate(), WORKING_START_TIME).plusDays(2); } if (endDateTime.getDayOfWeek() == DayOfWeek.SUNDAY) { endDateTime = LocalDateTime.of(endDateTime.toLocalDate(), WORKING_START_TIME).plusDays(1); } // 跨天处理 if (startDateTime.getDayOfYear() == endDateTime.getDayOfYear()) { int diffSecond = getDiffSecond(startDateTime, endDateTime); diff = diffSecond + diff; break; } int diffSecond = getDiffSecond(startDateTime, LocalDateTime.of(startDateTime.toLocalDate(), WORKING_END_TIME)); diff = diffSecond + diff; startDateTime = LocalDateTime.of(startDateTime.toLocalDate(), WORKING_START_TIME).plusDays(1); } return (Integer.valueOf(diff) / 3600); } public static int getDiffSecond(LocalDateTime startDateTime, LocalDateTime endDateTime) { LocalTime startTime = startDateTime.toLocalTime(); LocalTime endTime = endDateTime.toLocalTime(); // diff单位:秒 int diff = 0; // 开始时间切移 if (startTime.isBefore(WORKING_START_TIME)) { startTime = WORKING_START_TIME; } else if (startTime.isAfter(NOON_BREAK_START_TIME) && startTime.isBefore(NOON_BREAK_END_TIME)) { startTime = NOON_BREAK_START_TIME; } else if (startTime.isAfter(WORKING_END_TIME)) { startTime = WORKING_END_TIME; } // 结束时间切移 if (endTime.isBefore(WORKING_START_TIME)) { endTime = WORKING_START_TIME; } else if (endTime.isAfter(NOON_BREAK_START_TIME) && endTime.isBefore(NOON_BREAK_END_TIME)) { endTime = NOON_BREAK_START_TIME; } else if (endTime.isAfter(WORKING_END_TIME)) { endTime = WORKING_END_TIME; } // 午休时间判断处理 if (startTime.compareTo(NOON_BREAK_START_TIME) <= 0 && endTime.compareTo(NOON_BREAK_END_TIME) >= 0) { diff = diff + 60 * 60; } diff = endTime.toSecondOfDay() - startTime.toSecondOfDay() - diff; return diff; }
3.时间类型、格式转换
/**
*将Date对象转换为LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date){
//将Date对象转换为LocalDateTime
Instant instant = date.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
return localDateTime;
}
/**
* 将LocalDateTime对象转换为Date对象
* @param localDateTime
* @return
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime){
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
Instant instant2 = zonedDateTime.toInstant();
Date date = Date.from(instant2);
return date;
}
//字符串转Date类型
public static Date stringToDate(String time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newTime = format.parse(time);
return newTime;
}
//Date类型转换成字符串
public static String dateToString(Date date){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTime = format.format(date);
return nowTime;
}
二.有关集合处理
import java.util.*;
public class ListUtils {
/**
* list 集合分组
*
* @param list 待分组集合
* @param groupBy 分组Key算法
* @param <K> 分组Key类型
* @param <V> 行数据类型
* @return 分组后的Map集合
*/
public static <K, V> Map<K, List<V>> groupBy(List<V> list, GroupBy<K, V> groupBy) {
return groupBy((Collection<V>) list, groupBy);
}
/**
* list 集合分组
*
* @param list 待分组集合
* @param groupBy 分组Key算法
* @param <K> 分组Key类型
* @param <V> 行数据类型
* @return 分组后的Map集合
*/
public static <K, V> Map<K, List<V>> groupBy(Collection<V> list, GroupBy<K, V> groupBy) {
Map<K, List<V>> resultMap = new LinkedHashMap<K, List<V>>();
for (V e : list) {
K k = groupBy.groupBy(e);
if (resultMap.containsKey(k)) {
resultMap.get(k).add(e);
} else {
List<V> tmp = new LinkedList<V>();
tmp.add(e);
resultMap.put(k, tmp);
}
}
return resultMap;
}
/**
* List分组
*
* @param <K> 返回分组Key
* @param <V> 分组行
*/
public interface GroupBy<K, V> {
K groupBy(V row);
}
/**
* 对list集合进行分页处理
*/
public static <T>List<T> pageLimit(List<T> list, Integer page, Integer size) {
List<T> collect = list.stream().skip((page - 1) * size).limit(size).
collect(Collectors.toList());
return collect;
}
}
三.jpa查询转换为非实体vo
@Slf4j
public class EntityUtils {
/**
* 将数组数据转换为实体类
* 此处数组元素的顺序必须与实体类构造函数中的属性顺序一致
*
* @param list 数组对象集合
* @param clazz 实体类
* @param <T> 实体类
* @param model 实例化的实体类
* @return 实体类集合
*/
public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz, Object model) {
List<T> returnList = new ArrayList<T>();
if (list.isEmpty()) return returnList;
Object[] co = list.get(0);
List<Map> attributeInfoList = getFiledsInfo(model);
Class[] c2 = new Class[attributeInfoList.size()];
if (attributeInfoList.size() != co.length) {
return returnList;
}
for (int i = 0; i < attributeInfoList.size(); i++) {
c2[i] = (Class) attributeInfoList.get(i).get("type");
}
try {
for (Object[] o : list) {
Constructor<T> constructor = clazz.getConstructor(c2);
returnList.add(constructor.newInstance(o));
}
} catch (Exception ex) {
log.error("实体数据转化为实体类发生异常:异常信息:{}", ex.getMessage());
return returnList;
}
return returnList;
}
private static Object getFieldValueByName(String fieldName, Object modle) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = modle.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(modle, new Object[]{});
return value;
} catch (Exception e) {
return null;
}
}
private static List<Map> getFiledsInfo(Object model) {
Field[] fields = model.getClass().getDeclaredFields();
List<Map> list = new ArrayList(fields.length);
Map infoMap = null;
for (int i = 0; i < fields.length; i++) {
infoMap = new HashMap(3);
infoMap.put("type", fields[i].getType());
infoMap.put("name", fields[i].getName());
infoMap.put("value", getFieldValueByName(fields[i].getName(), model));
list.add(infoMap);
}
return list;
}
}
//将List<Object[]>转化为 List<XXX>
public static <T> List<T> HandEntity(List<Object[]> objectArrayResults, Class<T> customResultClass) {
List<T> customResults = new ArrayList<>();
try {
Constructor<T> constructor = customResultClass.getDeclaredConstructor();
Field[] fields = customResultClass.getDeclaredFields();
for (Object[] result : objectArrayResults) {
T customResult = constructor.newInstance();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true); // 设置字段为可访问
Object value = (i < result.length) ? result[i] : null; // 处理可能为空的字段
field.set(customResult, value);
}
customResults.add(customResult);
}
} catch (Exception e) {
e.printStackTrace();
}
return customResults;
}
四.把字符串中的汉字和数字分开
/**
* 取出字符串中的数字和汉字
* @param source
* @return
*/
public static ContactsVo handleString1(String source){
StringBuffer characters = new StringBuffer();
StringBuffer letter = new StringBuffer();
StringBuffer number = new StringBuffer();
char[] strArr = source.toCharArray();
ContactsVo contactsVo = new ContactsVo();
for (char string : strArr) {
// 判断是否为字母
if ((string+"").matches("[a-z]") || (string+"").matches("[A-Z]")){
letter.append(string);
}
// 判断是否为数字
if ((string+"").matches("[0-9]")){
number.append(string);
}
// 判断是否为汉字
if (isChineseChar(string+"")){
characters.append(string);
}
}
contactsVo.setContactsId(number.toString());
contactsVo.setUserFullName(characters.toString());
return contactsVo;
}
/**
* 判断是否为汉字
* @param str
* 字符串
* @return
*/
public static boolean isChineseChar(String str){
boolean temp = false;
Pattern p=Pattern.compile("[\u4e00-\u9fa5]");
Matcher m=p.matcher(str);
if(m.find()){
temp = true;
}
return temp;
}


被折叠的 条评论
为什么被折叠?



