代码

//计算日期差,不超过5分钟
long diff = Math.abs(CommonDateUtil.diff(new Date(), time, CommonDateUtil.MINUTE_MS));
		if (diff < 0 || diff > 5) {
			return "已过期,请更新时间戳";
		}

工具

package org.springblade.modules.api.utils;

import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 通用工具类
 *
 * @author Chill
 */
public class CommonDateUtil {
	private  final static String FIRST="1";
	private final  static String SECOND="2";
	private final  static String THIRD="3";
	private final static String FOUR="4";

	/** 毫秒 */
	private final static long MS = 1;
	/** 每秒钟的毫秒数 */
	private final static long SECOND_MS = MS * 1000;
	/** 每分钟的毫秒数 */
	public final static long MINUTE_MS = SECOND_MS * 60;



	/**
	 * 不够位数的在前面补0,保留num的长度位数字
	 *
	 * @param code 码
	 * @return 编号
	 */
	public static String autoGenericCode(String code, int num) {
		String result = "";
		result = String.format("%0" + num + "d", Integer.parseInt(code));
		return result;
	}


	/**
	 * 获取季度
	 * @param date 当前日期
	 * @return 季度
	 * @throws ParseException
	 */
	public static String getQuarter(LocalDateTime date) throws ParseException {
		if (Func.isEmpty(date)) {
			throw new RuntimeException("日期不能为空");
		}
		String quarter="";
		int month= Func.toInt(DateUtil.format(date,"M"));
		if(month>=1&&month<=3){
			quarter= date.getYear()+FIRST;
		}
		if(month>=4&&month<=6){
			quarter= date.getYear()+SECOND;
		}
		if(month>=7&&month<=9){
			quarter= date.getYear()+THIRD;
		}
		if(month>=10&&month<=12){
			quarter=date.getYear()+FOUR;
		}
		return quarter;
	}



	/**
	 * 获取百分比
	 * @param num1
	 * @param num2
	 * @return
	 */
	public static String TransPercent(int num1,int num2){
		DecimalFormat df =new DecimalFormat();
		df.setMaximumFractionDigits(1);
		df.setMinimumFractionDigits(1);
		if(num2==0){
			return "0%";
		}else{
			String percent = df.format(num1 *100.0 / num2) +"%";
			return percent;
		}
	}



	/**
	 * 字符串转换数字
	 *
	 * @param id
	 * @return
	 */
	public static Integer parseInt(String id) {
		Integer uId = 0;

		if (id == null || "".equals(id))
			return -1;

		try {
			uId = Integer.parseInt(id);
		} catch (NumberFormatException e) {
			// e.printStackTrace();
			uId = -1;
		}

		return uId;
	}

	/**
	 * 解析前台传来的数据。格式: 1,2,3
	 *
	 * @param param
	 * @return
	 */
	public static Integer[] parseParmas(String param) {
		Objects.requireNonNull(param);

		Integer[] idList = null;

		try {
			String id = URLDecoder.decode(param, "utf-8");
			Objects.requireNonNull(id);

			String[] ids = id.split(",");
			int len = ids.length;
			idList = new Integer[len];
			for (int i = 0; i < len; i++) {
				idList[i] = Integer.parseInt(ids[i].trim());
			}
		} catch (NumberFormatException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return idList;
	}

	/**
	 * 非空转换
	 *
	 * @param value
	 * @return
	 */
	public static String noEmpty(Object value) {
		return Optional.ofNullable(value)
				.map(v -> v.toString())
				.orElse("");
	}

	/**
	 * 非空转换
	 *
	 * @param value
	 * @return
	 */
	public static Integer noEmpty(Integer value) {
		return value == null ? 0 : value;
	}

	/**
	 * LocalDateTime 转换为 Date
	 *
	 * @param localDateTime
	 * @return
	 */
	public static Date LocalDateTimeToDate(LocalDateTime localDateTime) {
		ZoneId zone = ZoneId.systemDefault();
		Instant instant = localDateTime.atZone(zone).toInstant();
		return Date.from(instant);
	}

	/**
	 * Date 转换为 LocalDateTime
	 *
	 * @param date
	 * @return
	 */
	public static LocalDateTime DateToLocalDateTime(Date date) {
		Instant instant = date.toInstant();
		ZoneId zone = ZoneId.systemDefault();
		return LocalDateTime.ofInstant(instant, zone);
	}

	/**
	 *
	 * @param dateTime
	 * @return
	 */
	public static String parseDateStr(LocalDateTime dateTime) {
		Objects.requireNonNull(dateTime);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = LocalDateTimeToDate(dateTime);
		return sdf.format(date);
	}

	/**
	 * 解析字符串格式的时间
	 * @param date
	 * @return
	 */
	public static Map<String, Object> parseDateStr(String date) {
		Objects.requireNonNull(date);

		Map<String, Object> dateMap = new HashMap<>();
		String[] values = date.split(",");
		if (values != null && values.length == 2) {
			String begin = values[0].trim();
			if (begin != null && begin.length() >= 10)
				begin = begin.substring(0, 10);
			dateMap.put("begin", begin);

			String end = values[1].trim();
			if (end != null && end.length() >= 10)
				end = end.substring(0, 10);
			dateMap.put("end", end);
		}
		return dateMap;
	}

	/**
	 * 解析逗号分隔的日期
	 *
	 * @param date
	 * @param isDate
	 * @return
	 */
	public static Map<String, Object> parseDate(String date, boolean isDate) {
		Map<String, Object> dateMap = new HashMap<>();
		if(date != null) {
			String[] values = date.split(",");
			if (values != null && values.length == 2) {
				String begin = values[0].trim();
				String end = values[1].trim();
				if (isDate) {
					try {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						Date beginDate = sdf.parse(values[0]);
						Date endDate = sdf.parse(values[1]);
						//结束日期加一天
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(endDate);
						calendar.add(Calendar.DATE, 1);
						endDate = calendar.getTime();
						dateMap.put("begin", DateToLocalDateTime(beginDate));
						dateMap.put("end", DateToLocalDateTime(endDate));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				} else {
					dateMap.put("begin", begin);
					dateMap.put("end", end);
				}
			}
		}
		return dateMap;
	}

	/**
	 * 获取对象的所有属性
	 *
	 * @param obj
	 * @return
	 */
	public static Field[] getFields(Object obj) {
		return getFields(obj, false);
	}

	/**
	 * 获取对象的所有属性,包括从父类继承的属性
	 *
	 * @param obj
	 * @param parent
	 * @return
	 */
	public static Field[] getFields(Object obj, boolean parent) {
		Objects.requireNonNull(obj);

		List<Field> fieldList = new ArrayList<>();
		Class<? extends Object> clazz = obj.getClass();

		while (clazz != null) {
			fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
			clazz = parent ? clazz.getSuperclass() : null;
		}

		Field[] fields = new Field[fieldList.size()];
		return fieldList.toArray(fields);
	}

	/**
	 * 获取通用对象字段的值
	 *
	 * @param object
	 * @param fieldName
	 * @return
	 * @throws NoSuchMethodException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static Object getFieldValue(Object object, String fieldName)
			throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		Objects.requireNonNull(object);

		Object value = null;
		String getName = capitalize(fieldName);
		if (notEmpty(getName)) {
			Method m = object.getClass().getMethod("get" + getName);
			value = m.invoke(object);
		}
		return value;
	}

	/**
	 * 验证字符串是否为空
	 *
	 * @param value
	 * @return
	 */
	public static boolean notEmpty(String value) {
		return value != null && !"".equals(value);
	}

	/**
	 * 首字母转换为大写
	 *
	 * @param fieldName
	 * @return
	 */
	public static String capitalize(String fieldName) {
		String getName = "";
		if (notEmpty(fieldName)) {
			getName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
		}

		return getName;
	}

	/**
	 * 从字符串开始处抽取指定长度的字符
	 *
	 * @param content
	 * @param len
	 * @return
	 */
	public static String extract(String content, int len) {
		return Optional.ofNullable(content)
				.filter(c -> c.length() > len)
				.map(c -> {
					StringBuffer buffer = new StringBuffer();
					buffer.append(c.substring(0, len)).append("...");
					return buffer.toString();
				}).orElse(content);
	}

	/**
	 * 字符串数据转为数字数组
	 * @param str
	 * @return
	 */
	public static Integer[] str2IntArray(String str) {
		String[] strs = str.split(",");
		Integer[] original = new Integer[strs.length];
		for (int i = 0, len = strs.length; i < len; i++) {
			original[i] = parseInt(strs[i]);
		}
		return original;
	}

	/**
	 * 计算占比
	 * @param num
	 * @param total
	 * @return
	 */
	public static Float calcPercent(int num, int total) {
		Float rate = (num * 10000.0f) / total;
		return ((new BigDecimal(rate).setScale(0, BigDecimal.ROUND_HALF_UP)).floatValue()) / 10000;
	}

	/**
	 * Check list not null
	 * @param list
	 * @return
	 */
	public static boolean validList(List<?> list) {
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	public static String deleteAllHTMLTag(String source) {
		if (source == null) {
			return "";
		}

		String s = source;
		/** 删除普通标签 */
		s = s.replaceAll("<(S*?)[^>]*>.*?|<.*? />", "");
		/** 删除转义字符 */
		s = s.replaceAll("&.{2,6}?;", "");

		return s;
	}

	public static Map<String, Map<String, Object>> mapAscSortedByKey(Map<String, Map<String, Object>> unsortMap) {
		Map<String, Map<String, Object>> result = new HashMap<>();

		if (unsortMap != null) {
			unsortMap.entrySet().stream().sorted(Map.Entry.<String, Map<String, Object>>comparingByKey())
					.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
		}

		return result;
	}

	public static Date strToDate(String dateStr) {
		return strToDate(dateStr, "yyyy-MM-dd");
	}

	public static Date strToDate(String dateStr, String format) {
		Date date = new Date();
		if (dateStr != null) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(format);
				date = sdf.parse(dateStr);
			} catch (ParseException e) {
				date = new Date();
			}
		}
		return date;
	}

	/**
	 *
	 * @param date
	 * @return
	 */
	public static String parseDateStr(Date date) {
		return parseDateStr(date, "yyyy-MM-dd");
	}

	public static String parseDateStr(Date date, String format) {
		String dateStr = "";
		if (date != null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			dateStr = sdf.format(date);
		}
		return dateStr;
	}

	public static double calcRate(long num, long total) {
		double rate = 0;
		if (num != 0) {
			try {
				double temp = (float) (num * 100) / total;
				BigDecimal b = new BigDecimal(temp);
				rate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			} catch (Exception e) {

			}
		}

		return rate;
	}

	public static String calcPerc(long num, long total) {
		String result = "0";
		if (total != 0) {
			if (num > total) {
				num = total;
			}

			try {
				// 创建一个数值格式化对象
				NumberFormat numberFormat = NumberFormat.getInstance();
				// 设置精确到小数点后2位
				numberFormat.setMaximumFractionDigits(2);
				result = numberFormat.format((float) num / (float) total * 100);
			} catch (Exception e) {
			}
		}

		return result + "%";
	}


    public  static  int objToInt(Object obj){
		if(obj==null){
			return 0;
		}

		if(obj instanceof Double){
			return  ((Double) obj).intValue();
		}
		if(obj instanceof  BigDecimal){
			return  ((BigDecimal) obj).intValue();
		}
		return  Integer.parseInt(obj.toString());
	};



	/**
	 * 等待线程结束
	 * @param workers
	 */
	public static  void joinThread(List<Thread> workers){
		//等待线程结束
		workers.forEach(e->{
			try {
				e.join();
			}catch (Exception ex){
				ex.printStackTrace();
			}finally {
				e.interrupt();
			}
		});

	}

	/**
	 * 计算日期差
	 * @param subtrahend
	 * @param minuend
	 * @param diffField
	 * @return
	 */
	public static long diff(Date subtrahend, Date minuend, long diffField) {
		long diff = minuend.getTime() - subtrahend.getTime();
		return diff / diffField;
	}
	/**
	 * 将时间戳变为日期
	 * @param s
	 * @return
	 */
	public static Date stampToDate(String s){
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long lt = new Long(s);
		Date date = new Date(lt);
		res = simpleDateFormat.format(date);
		return DateUtil.parse(res, DateUtil.PATTERN_DATETIME);
	}




}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐