package org.springblade.common.utils;import org.springblade.core.tool.utils.Func;import java.math.BigDecimal;import java.math.RoundingMode;import java.text.DateFormat;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.util.*;import java.util.regex.Pattern;/** * What:高频常用方法集合<br> * Where:xx.xxx简短快捷的输入操作<br> * Why:整合高频常用方法,编码速度+50%,代码量-70% * */public class XX { /** * 对象是否为空 * * @param o String,List,Map,Object[],int[],long[] * @return */ @SuppressWarnings("rawtypes") public static boolean isEmpty(Object o) { if (o == null) { return true; } if (o instanceof String) { if (o.toString().trim().equals("")) { return true; } } else if (o instanceof List) { if (((List) o).size() == 0) { return true; } } else if (o instanceof Map) { if (((Map) o).size() == 0) { return true; } } else if (o instanceof Set) { if (((Set) o).size() == 0) { return true; } } else if (o instanceof Object[]) { if (((Object[]) o).length == 0) { return true; } } else if (o instanceof int[]) { if (((int[]) o).length == 0) { return true; } } else if (o instanceof long[]) { if (((long[]) o).length == 0) { return true; } } else if (o instanceof Integer) { if (o.toString().trim().equals("0")) { return true; } } return false; } /** * 对象组中是否存在 Empty Object * * @param os 对象组 * @return */ public static boolean isOneEmpty(Object... os) { for (Object o : os) { if (isEmpty(o)) { return true; } } return false; } /** * 对象组中是否全是 Empty Object * * @param os * @return */ public static boolean isAllEmpty(Object... os) { for (Object o : os) { if (!isEmpty(o)) { return false; } } return true; } /** * 是否为数字 * * @param obj * @return */ public static boolean isNum(Object obj) { try { Integer.parseInt(obj.toString()); } catch (Exception e) { return false; } return true; } /** * 字符串是否为 true * * @param str * @return */ public static boolean isTrue(Object str) { if (isEmpty(str)) { return false; } str = str.toString().trim().toLowerCase(); if (str.equals("true") || str.equals("on")) { return true; } return false; } /** * 格式化字符串->'str' * * @param str * @return */ public static String format(Object str) { return "'" + str.toString() + "'"; } /** * 强转->java.util.Date * * @param str 日期字符串 * @return */ public static Date toDate(String str) { try { if (str == null || "".equals(str.trim())) return null; return new SimpleDateFormat("yyyy-MM-dd").parse(str.trim()); } catch (Exception e) { throw new RuntimeException("Can not parse the parameter \"" + str + "\" to Date value."); } } //yyyy-MM-dd HH:mm:ss转date// public static Date strToDate(String strDate) {// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// ParsePosition pos = new ParsePosition(0);// Date strtodate = formatter.parse(strDate, pos);// return strtodate;// } /** * Array转字符串(用指定符号分割) * * @param array * @param sign * @return */ public static String join(Object[] array, char sign) { if (array == null) { return null; } int arraySize = array.length; int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize); StringBuilder sb = new StringBuilder(bufSize); for (int i = 0; i < arraySize; i++) { if (i > 0) { sb.append(sign); } if (array[i] != null) { sb.append(array[i]); } } return sb.toString(); } /** * 删除末尾字符串 * * @param str 待处理字符串 * @param sign 需要删除的符号 * @return */ public static String delEnd(String str, String sign) { if (str.endsWith(sign)) { return str.substring(0, str.lastIndexOf(sign)); } return str; } /** * 消耗毫秒数 * * @param time */ public static void costTime(long time) { System.err.println("Load Cost Time:" + (System.currentTimeMillis() - time) + "ms\n"); } /** * 格式化输出JSON * * @param json * @return */ public static String formatJson(String json) { int level = 0; StringBuffer sb = new StringBuffer(); for (int i = 0; i < json.length(); i++) { char c = json.charAt(i); if (level > 0 && '\n' == sb.charAt(sb.length() - 1)) { sb.append(getLevelStr(level)); } switch (c) { case '{': case '[': sb.append(c + "\n"); level++; break; case ',': sb.append(c + "\n"); break; case '}': case ']': sb.append("\n"); level--; sb.append(getLevelStr(level)); sb.append(c); break; default: sb.append(c); break; } } return sb.toString(); } private static String getLevelStr(int level) { StringBuffer levelStr = new StringBuffer(); for (int levelI = 0; levelI < level; levelI++) { levelStr.append(" "); } return levelStr.toString(); } /** * 获取当前时间 * * @param formater 格式 * @return */ public static String getFormatTime(String formater, String time) { Date date = StrToDate(time); DateFormat format = new SimpleDateFormat(formater); return format.format(date); } public static String getFormatTime(String formater, Date time) { DateFormat format = new SimpleDateFormat(formater); return format.format(time); } public static Date StrToDate(String str) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(str); } catch (Exception e) { e.printStackTrace(); } return date; } public static String DateToStr(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = null; if (Func.isNotEmpty(date)){ str=format.format(date); } return str; } /** * 获取当前时间:yyyy-MM-dd HH:mm:ss * * @return */ public static String getCurrentTime() { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } public static String dateToStr(Date date) { if(date == null){ return null; }else{ DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } } /** * 获取当前日期:yyyy-MM-dd * * @return */ public static String getCurrentDate() { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(date); } /** * 获取当前时间 * * @param formater 格式 * @return */ public static String getCurrentTime(String formater) { Date date = new Date(); DateFormat format = new SimpleDateFormat(formater); return format.format(date); } /** * 计算两经纬度点之间的距离(单位:米) * * @param lng1 经度 * @param lat1 纬度 * @param lng2 * @param lat2 * @return getDistance(117.129135, 36.68824, 117.12843556, 36.68851556) */ public static double getDistance(double lng1, double lat1, double lng2, double lat2) { double radLat1 = Math.toRadians(lat1); double radLat2 = Math.toRadians(lat2); double a = radLat1 - radLat2; double b = Math.toRadians(lng1) - Math.toRadians(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * 6378137.0;// 取WGS84标准参考椭球中的地球长半径(单位:m) s = Math.round(s * 10000) / 10000; return s; } public static boolean isInteger(String str) { Pattern pattern = Pattern.compile("^-?[0-9]+"); return pattern.matcher(str).matches(); } public static long getDistanceTime(String str1, Date date) { return getDistanceTime(str1, dateToStr(date) ); } //返回两个时间差 分钟 public static long getDistanceTime(String str1, String str2) { if (XX.isEmpty(str1) || XX.isEmpty(str2)) { return 0; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date one; Date two; long min = 0; try { one = df.parse(str1); two = df.parse(str2); long time1 = one.getTime(); long time2 = two.getTime(); long diff; if (time1 < time2) { diff = time2 - time1; } else { diff = time1 - time2; } min = diff / (60 * 1000); } catch (Exception e) { e.printStackTrace(); } return min; } //返回输入日期与当前日期的差 天 public static int getDistanceTime(String str){ if (XX.isEmpty(str)){ return 0; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String currentTimeString = simpleDateFormat.format(new Date()); int deviation=0; try { Date currentTime = simpleDateFormat.parse(currentTimeString); Date parseTime = simpleDateFormat.parse(str); BigDecimal timeReduction = new BigDecimal(parseTime.getTime() - currentTime.getTime()); BigDecimal timeDivide = timeReduction.divide(new BigDecimal(1000 * 3600 * 24), 0, RoundingMode.UP); deviation = timeDivide.intValue(); } catch (Exception e) { e.printStackTrace(); } return deviation; } public static double getStr2Double(String str) { double ret = 0; try { ret = Double.parseDouble(str); } catch (Exception e) { } return ret; } //获取xxx分钟之后的时间 public static String getAfterTime(String strTime, int minute) { String oneMinuteAfterTime = ""; Calendar cal = Calendar.getInstance(); cal.setTime(XX.StrToDate(strTime)); //cal.set(cal.HOUR , cal.HOUR -hour ) ; //把时间设置为当前时间-1小时,同理,也可以设置其他时间 cal.add(cal.MINUTE, minute); oneMinuteAfterTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());//获取到完整的时间 return oneMinuteAfterTime; } //获取小时之后的时间 public static String getAfterTimeOfHour(String strTime, int hour) { String afterTimeOfHour = ""; Calendar cal = Calendar.getInstance(); cal.setTime(XX.StrToDate(strTime)); cal.add(Calendar.HOUR, hour); afterTimeOfHour = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());//获取到完整的时间 return afterTimeOfHour; } //比较时间大小 public static Boolean CompareDate(Date dateOne, Date dateTwo) { boolean flag = dateOne.getTime() >= dateTwo.getTime(); return flag; } public static double getTimeDiff(Date time1, Date time2) { long t1 = time1.getTime(); long t2 = time2.getTime(); double ret = 0; if (t1 > t2) { ret = (t1 - t2) / (60 * 60 * 1000); } else { ret = (t2 - t1) / (60 * 60 * 1000); } return ret; } public static String formatNum(String text, double value) { DecimalFormat myformat = new DecimalFormat(text); String output = myformat.format(value); return output; } public static long differentTimesByMillisecond(Date date1, Date date2, int flag) { long result = 0; long time1 = date1.getTime(); long time2 = date2.getTime(); switch (flag) { case 0://毫秒 result = time2 - time1; break; case 1://秒 result = (time2 - time1) / 1000; break; case 2://分钟 result = (time2 - time1) / (1000 * 60); break; case 3://小时 result = (time2 - time1) / (1000 * 60 * 60); break; case 4://天 result = (time2 - time1) / (1000 * 3600 * 24); break; default: result = (time2 - time1) / (1000 * 60); break; } return result; } /** * java.time.LocalDateTime --> java.util.Date * @param localDateTime * @return */ public static Date localDateTimeToDate(LocalDateTime localDateTime) { if (isEmpty(localDateTime)) localDateTime = LocalDateTime.now(); ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); Date date = Date.from(instant); return date; } /** * java.util.Date --> java.time.LocalDateTime * @param date * @return */ public static LocalDateTime localDateTimeToDate(Date date) { Instant instant = Instant.ofEpochMilli(date.getTime()); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } /** * 强转->Double * @param obj * @return */ public static double toDouble(Object obj) { if(XX.isEmpty(obj)) { return 0; } return Double.parseDouble(obj.toString()); } /** * 把map的key转换成驼峰命名 * @param map * @return */ public static Map<String, Object> toReplaceKeyLow(Map<String, Object> map) { Map re_map = new HashMap(); if (re_map != null) { Iterator var2 = map.entrySet().iterator(); while (var2.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry) var2.next(); re_map.put(underlineToCamel((String) entry.getKey()), map.get(entry.getKey())); } map.clear(); } return re_map; } public static final char UNDERLINE = '_'; public static String underlineToCamel(String param) { if (param == null || "".equals(param.trim())) { return ""; } int len = param.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = param.charAt(i); if (c == UNDERLINE) { if (++i < len) { sb.append(Character.toUpperCase(param.charAt(i))); } } else { sb.append(Character.toLowerCase(param.charAt(i))); } } return sb.toString(); } //比较两个时间大小 //dt1 在dt2前 true public static boolean compareDate(Date dt1, Date dt2) { try { if (dt1.getTime() < dt2.getTime()) { return true; } else if (dt1.getTime() > dt2.getTime()) { return false; } } catch (Exception exception) { exception.printStackTrace(); } return false; } /** * 封装查询条件,解决字段默认like查询问题 * @param query * @param column * @param exp * @return */ public static Map<String, Object> getSQLColumn(Map<String, Object> query,String column,String exp) { if (!isEmpty(query) && !isEmpty(column) && !isEmpty(exp) && !isEmpty(query.get(column))) { Object value = query.get(column); query.remove(column); query.put(column + exp,value); return query; } return new HashMap<String,Object>(); } /** * 获取当月的第一天_格式yyyy-MM-dd * @param datePattern * @return */ public static String getFirstMonth(String datePattern){ SimpleDateFormat df=new SimpleDateFormat(datePattern); GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance(); Date date = new Date(); gc.setTime(date); gc.set(Calendar.DAY_OF_MONTH, 1); String day_first = df.format(gc.getTime()); return day_first; } /** * 获取当月的最后一天_格式yyyy-MM-dd * @param datePattern * @return */ public static String getEndMonth(String datePattern){ SimpleDateFormat df=new SimpleDateFormat(datePattern); GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance(); Date date = new Date(); gc.setTime(date); gc.add(Calendar.MONTH, 1); gc.set(Calendar.DAY_OF_MONTH, 0); String day_end = df.format(gc.getTime()); return day_end; }}