Java常用工具类

List分页工具类

package com.cn.ih.java.main.utils;

import com.cn.ih.java.main.webservice.vo.Page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author qingshi
 * @date 2022/10/13 16:36
 * info:
 */
public class ListUtils {
    /**
     * 对List分页
     */
    public static List<Object> getDataBetweenIndex(Integer total, Integer current, Integer size, List<Object> str){
        List<Object> result = new ArrayList<>();
        //获取初始化分页结构
        com.cn.ih.java.main.webservice.vo.Page<String> page = new Page<>().getPage(total, size, current - 1);
        //获取集合下标初始值
        long startIndex = page.getStartIndex();
        //获取集合下标结束值
        long endInddex = 0;
        /**
         * 如果初始值startIndex(size * current)超过总记录数 或者 入参size(一页显示多少条)大于总记录树,
         * 则下标结束值均设置为集合大小
         */
        if(startIndex + page.getCurrent() >= total || size > total){
            endInddex = total;
        }else {
            /**当最后一页,开始下标加上要取值的size 大于总条数,则最终索引改为集合大小-1=》为
             *集合的最后下标值,防止下标溢出
             **/
            if(total < startIndex + page.getSize()){
                endInddex = total - 1 ;
            }else {
                //否则为startIndex(size * current 从哪里开始取)加上一页显示多少条得到结束值
                endInddex = startIndex  + page.getSize();
            }
        }
        //如果输入的开始查询下标大于集合大小,则查询为空值
        if(startIndex > total){
            result = Collections.emptyList();
        }else{
            result = str.subList((int)startIndex,(int)endInddex);
        }
        /**
         * 此处返回结果可以改为Page<T> T为对应业务的实体类型,最终把分页结果再塞入page的records再返回则得到与
         * mybatisplus一样的结构
         *  page.setRecords(list);
         *  return page;
         */
        return result;
    }
}

分页后返回的是List类型,可以如果以下方法转换为对应的实体类

import com.fasterxml.jackson.databind.ObjectMapper;

InquiryOrder inquiryOrder = new ObjectMapper().convertValue(obj, InquiryOrder.class);
其中InquiryOrder为要转换的实体类对象

Page 实体类

package com.cn.ih.java.main.webservice.vo;

import java.io.Serializable;
import java.util.List;

/**
 * @author qingshi
 * @date 2022/10/13 16:43
 * info:
 */
public class Page<T> implements Serializable {
    private List<T> records; //最终查询的结果记录
    private long total; //共有多少条记录
    private long size;  //一页显示多少条
    private long current; //取第几页显示
    private long pages; //总共几页
    private long startIndex; //从哪里开始截取集合的下标
    //获取初始化分页对象 这里用long类型是为了与mybatisplus保持一致
    public Page<String> getPage(long total, long size ,long current){
        Page<String> page = new Page<>();
        page.setTotal(total);
        page.setSize(size);
        //总页数的计算 如果集合总记录数能被入参size(一页几条)整除,则为对应商,否则多出部分也独立算一页
        page.setPages(total % size == 0 ? total / size : total / size + 1);
        //前端约定入参从1开始,但此处入参调用时会减1,此处+1恢复原值供前端展示
        page.setCurrent(current + 1);
        //开始索引的设置
        page.setStartIndex(size * current);
        return page;
    }

    public List<T> getRecords() {
        return records;
    }

    public void setRecords(List<T> records) {
        this.records = records;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public long getCurrent() {
        return current;
    }

    public void setCurrent(long current) {
        this.current = current;
    }

    public long getPages() {
        return pages;
    }

    public void setPages(long pages) {
        this.pages = pages;
    }

    public long getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(long startIndex) {
        this.startIndex = startIndex;
    }
}

Map排序工具类

package com.cn.ih.java.main.utils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author qingshi
 * @date 2022/10/13 8:46
 * info:
 */
public class MapSortUtils {
    /**
     * 根据map中的value大小进行排序【由大到小】
     */
    public static <K extends Comparable,V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> map){
        //需要用LinkedHashMap排序
        HashMap<K, V> finalMap = new LinkedHashMap<K, V>();
        //取出map键值对Entry<K,V>,然后按照值排序,最后组成一个新的列表集合
        List<Map.Entry<K, V>> list = map.entrySet()
                .stream()
                //sorted((p2,p1)   表示由大到小排序   ||  sorted((p1,p2)   表示由小到大排序
                .sorted((p1,p2)->p1.getValue().compareTo(p2.getValue()))
                .collect(Collectors.toList());
        //遍历集合,将排好序的键值对Entry<K,V>放入新的map并返回。
        list.forEach(ele->finalMap.put(ele.getKey(), ele.getValue()));
        return finalMap;
    }
}

时间通用工具类

package com.cn.ih.java.main.utils;

import java.text.*;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;

import org.springframework.util.StringUtils;

/**
 * @author Wurd 2005-11-27
 *
 * 日期帮助�?
 */
public class TimeHelper {
	private static String CurrentTime;

	private static String CurrentDate;
	/**
	 *
	 * TODO(object �?String)
	 *
	 * @param obj
	 * @return
	 */
	public static String convertToString(Object obj) {
		if (obj == null)
			return "";
		String str = obj.toString().trim();
		if (str.equals("null") || str.equals("NULL"))
			return "";
		return str;
	}

	public static String getYear(java.util.Date NowDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		return formatter.format(NowDate);
	}

	public static String getMonth(java.util.Date NowDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("MM");
		return formatter.format(NowDate);
	}
	public static String getDay(java.util.Date NowDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("dd");
		return formatter.format(NowDate);
	}

	/**
	 * 得到当前的年�?返回格式:yyyy
	 *
	 * @return String
	 */
	public static String getCurrentYear() {
		java.util.Date NowDate = new java.util.Date();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		return formatter.format(NowDate);
	}

	/**
	 * 得到当前的月�?返回格式:MM
	 *
	 * @return String
	 */
	public static String getCurrentMonth() {
		java.util.Date NowDate = new java.util.Date();

		SimpleDateFormat formatter = new SimpleDateFormat("MM");
		return formatter.format(NowDate);
	}

	/**
	 * 得到前/后月?返回格式:MM
	 *
	 * @return String
	 */
	public static String getCurrentMonthBeforeOrAfter(int i) {
		//过去一月
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.MONTH, i);
		Date m = c.getTime();
		return format.format(m);
	}


	/**
	 * 得到当前的日�?返回格式:dd
	 *
	 * @return String
	 */
	public static String getCurrentDay() {
		java.util.Date NowDate = new java.util.Date();

		SimpleDateFormat formatter = new SimpleDateFormat("dd");
		return formatter.format(NowDate);
	}
	/**
	 * 得到当前的时间,精确到毫�?�?9�?返回格式:yyyy-MM-dd HH:mm:ss
	 *
	 * @return String
	 */
	public static String getCurrentTime() {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CurrentTime = formatter.format(NowDate);
		return CurrentTime;
	}

	/**
	 * 得到当前的时间的编号,精确到毫�?�?9�?返回格式:yyyy-MM-dd HH:mm:ss
	 *
	 * @return String
	 */
	public static String getCurrentOrder() {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		CurrentTime = formatter.format(NowDate);
		return CurrentTime;
	}

	/**
	 * 得到当前的时间,精确到小时 返回格式:yyyy-MM-dd HH
	 *
	 * @return String
	 */
	public static String getCurrentHour() {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH");
		CurrentTime = formatter.format(NowDate);
		return CurrentTime;
	}

	/**
	 * 得到当前的时间,精确到毫�?�?9�?返回格式:yyyy-MM-dd HH:mm:ss
	 *
	 * @return String
	 */
	public static String getCurrentTimeOfFormat(String format) {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		CurrentTime = formatter.format(NowDate);
		return CurrentTime;
	}

	public static String getCurrentCompactTime() {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		CurrentTime = formatter.format(NowDate);
		return CurrentTime;
	}
	public static String getYesterdayCompactTime() {
		Calendar cal = Calendar.getInstance();
		cal.add(cal.DATE, -1);
		System.out.print(cal.getTime());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		CurrentTime = formatter.format(cal.getTime());
		return CurrentTime;
	}
	public static String getYesterdayCompactTimeForFileName() {
		Calendar cal = Calendar.getInstance();
		cal.add(cal.DATE, -1);
		System.out.print(cal.getTime());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CurrentTime = formatter.format(cal.getTime());
		return CurrentTime;
	}
	/**
	 * 得到当前的日�?�?0�?返回格式:yyyy-MM-dd
	 *
	 * @return String
	 */
	public static String getCurrentDate() {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		CurrentDate = formatter.format(NowDate);
		return CurrentDate;
	}

	/**
	 * 得到当月的第�?��,�?0�?返回格式:yyyy-MM-dd
	 *
	 * @return String
	 */
	public static String getCurrentFirstDate() {
		Date NowDate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-01");
		CurrentDate = formatter.format(NowDate);
		return CurrentDate;
	}

	/**
	 * 得到当月的最后一�?�?0�?返回格式:yyyy-MM-dd
	 *
	 * @return String
	 * @throws ParseException
	 */
	public static String getCurrentLastDate() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar=null;
		try {
			java.util.Date date =formatter.parse(getCurrentFirstDate());
			calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MONTH,1);
			calendar.add(Calendar.DAY_OF_YEAR, -1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return formatDate(calendar.getTime());

	}

	/**
	 * 校验日期格式是否正确
	 * @param dateStr
	 * @return
	 */
	public static boolean validDateStr(String dateStr) {
		try {
			LocalDate.parse(dateStr, new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").parseStrict().toFormatter());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static java.util.Date getFistDate(java.util.Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-01");
		return  parseDate(formatter.format(date));
	}

	public static java.util.Date getLastDate(java.util.Date date1) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar=null;
		java.util.Date date =getFistDate(date1);
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH,1);
		calendar.add(Calendar.DAY_OF_YEAR, -1);
		return parseDate(formatDate(calendar.getTime()));
	}


	/**
	 * 常用的格式化日期
	 *
	 * @param date Date
	 * @return String
	 */
	public static String formatDate(java.util.Date date)
	{
		return formatDateByFormat(date,"yyyy-MM-dd");
	}
	/**
	 * 以指定的格式来格式化日期
	 *
	 * @param date Date
	 * @param format String
	 * @return String
	 */
	public static String formatDateByFormat(java.util.Date date,String format)
	{
		String result = "";
		if(date != null)
		{
			try
			{
				SimpleDateFormat sdf = new SimpleDateFormat(format);
				result = sdf.format(date);
			}
			catch(Exception ex)
			{

				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String formatstrDateByFormat(String strdate,String format)
	{
		String result = "";
		if(!StringUtils.isEmpty(strdate))
		{
			try
			{    java.util.Date date=TimeHelper.parseDate(strdate);
				SimpleDateFormat sdf = new SimpleDateFormat(format);
				result = sdf.format(date);
			}
			catch(Exception ex)
			{

				ex.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * 得到当前日期加上某一个整数的日期,整数代表天�?输入参数:currentdate : String 格式 yyyy-MM-dd add_day :
	 * int 返回格式:yyyy-MM-dd
	 */
	public static String addDay(String currentdate, int add_day) {
		GregorianCalendar gc = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		int year, month, day;

		try {
			year = Integer.parseInt(currentdate.substring(0, 4));
			month = Integer.parseInt(currentdate.substring(5, 7)) - 1;
			day = Integer.parseInt(currentdate.substring(8, 10));

			gc = new GregorianCalendar(year, month, day);
			gc.add(GregorianCalendar.DATE, add_day);

			return formatter.format(gc.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 得到当前日期加上某一个整数的日期,整数代表月�?输入参数:currentdate : String 格式 yyyy-MM-dd add_month :
	 * int 返回格式:yyyy-MM-dd
	 */
	public static String addMonth(String currentdate, int add_month) {
		GregorianCalendar gc = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		int year, month, day;

		try {
			year = Integer.parseInt(currentdate.substring(0, 4));
			month = Integer.parseInt(currentdate.substring(5, 7)) - 1;
			day = Integer.parseInt(currentdate.substring(8, 10));

			gc = new GregorianCalendar(year, month, day);
			gc.add(GregorianCalendar.MONTH, add_month);

			return formatter.format(gc.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 得到endTime比beforeTime晚几个月,整数代表月�?输入参数:endTime、beforeTime : String 格式�?位的格式�?yyyy-MM
	 */
	public static int monthDiff(String beforeTime,String endTime){
		if(beforeTime==null||endTime==null){
			return 0;
		}
		int beforeYear,endYear,beforeMonth,endMonth;
		try {
			beforeYear = Integer.parseInt(beforeTime.substring(0, 4));
			endYear = Integer.parseInt(endTime.substring(0, 4));
			beforeMonth = Integer.parseInt(beforeTime.substring(5, 7)) - 1;
			endMonth = Integer.parseInt(endTime.substring(5, 7)) - 1;
			return (endYear-beforeYear)*12+(endMonth-beforeMonth);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 得到当前日期加上某一个整数的分钟 输入参数:currentdatetime : String 格式 yyyy-MM-dd HH:mm:ss
	 * add_minute : int 返回格式:yyyy-MM-dd HH:mm:ss
	 */
	public static String addMinute(String currentdatetime, int add_minute) {
		GregorianCalendar gc = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int year, month, day, hour, minute, second;

		try {
			year = Integer.parseInt(currentdatetime.substring(0, 4));
			month = Integer.parseInt(currentdatetime.substring(5, 7))-1;
			day = Integer.parseInt(currentdatetime.substring(8, 10));

			hour = Integer.parseInt(currentdatetime.substring(11, 13));
			minute = Integer.parseInt(currentdatetime.substring(14, 16));
			second = Integer.parseInt(currentdatetime.substring(17, 19));

			gc = new GregorianCalendar(year, month, day, hour, minute, second);
			gc.add(GregorianCalendar.MINUTE, add_minute);

			return formatter.format(gc.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static String addMinute2(String currentdatetime, int add_minute) {
		GregorianCalendar gc = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int year, month, day, hour, minute, second;

		try {
			year = Integer.parseInt(currentdatetime.substring(0, 4));
			month = Integer.parseInt(currentdatetime.substring(5, 7))-1;
			day = Integer.parseInt(currentdatetime.substring(8, 10));

			hour = Integer.parseInt(currentdatetime.substring(11, 13));
			minute = Integer.parseInt(currentdatetime.substring(14, 16));

			gc = new GregorianCalendar(year, month, day, hour, minute);
			gc.add(GregorianCalendar.MINUTE, add_minute);

			return formatter.format(gc.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 得到当前日期加上某一个整数的�?输入参数:currentdatetime : String 格式 yyyy-MM-dd HH:mm:ss
	 * add_second : int 返回格式:yyyy-MM-dd HH:mm:ss
	 */
	public static String addSecond(String currentdatetime, int add_second) {
		GregorianCalendar gc = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int year, month, day, hour, minute, second;

		try {
			year = Integer.parseInt(currentdatetime.substring(0, 4));
			month = Integer.parseInt(currentdatetime.substring(5, 7))-1;
			day = Integer.parseInt(currentdatetime.substring(8, 10));

			hour = Integer.parseInt(currentdatetime.substring(11, 13));
			minute = Integer.parseInt(currentdatetime.substring(14, 16));
			second = Integer.parseInt(currentdatetime.substring(17, 19));

			gc = new GregorianCalendar(year, month, day, hour, minute, second);
			gc.add(GregorianCalendar.SECOND, add_second);

			return formatter.format(gc.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String addMinute1(String currentdatetime, int add_minute) {
		GregorianCalendar gc = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		int year, month, day, hour, minute, second;

		try {
			year = Integer.parseInt(currentdatetime.substring(0, 4));
			month = Integer.parseInt(currentdatetime.substring(5, 7)) - 1;
			day = Integer.parseInt(currentdatetime.substring(8, 10));

			hour = Integer.parseInt(currentdatetime.substring(8, 10));
			minute = Integer.parseInt(currentdatetime.substring(8, 10));
			second = Integer.parseInt(currentdatetime.substring(8, 10));

			gc = new GregorianCalendar(year, month, day, hour, minute, second);
			gc.add(GregorianCalendar.MINUTE, add_minute);

			return formatter.format(gc.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static Date parseDate(String sDate) {
		SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		try {
			Date date = bartDateFormat.parse(sDate);
			return date;
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return null;
	}

	/**
	 * 解析日期及时�?
	 *
	 * @param sDateTime
	 *            日期及时间字符串
	 * @return 日期
	 */
	public static Date parseDateTime(String sDateTime) {
		SimpleDateFormat bartDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		try {
			Date date = bartDateFormat.parse(sDateTime);
			return date;
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return null;
	}
	/**
	 *  java 获取 获取某年某月 所有日期(yyyy-mm-dd格式字符串)
	 * @param yearmonth
	 * @return
	 */
	public static List<String> getMonthFullDay(String yearmonth){
		String[] split = yearmonth.split("-");
		int year = Integer.parseInt(split[0]);
		int month = Integer.parseInt(split[1]);
		SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
		List<String> fullDayList = new ArrayList<>(32);
		// 获得当前日期对象
		Calendar cal = Calendar.getInstance();
		cal.clear();// 清除信息
		cal.set(Calendar.YEAR, year);
		// 1月从0开始
		cal.set(Calendar.MONTH, month-1 );
		// 当月1号
		cal.set(Calendar.DAY_OF_MONTH,1);
		int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		for (int j = 1; j <= count ; j++) {
			fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
			cal.add(Calendar.DAY_OF_MONTH,1);
		}
		return fullDayList;
	}
	/**
	 * 取得�?��月的天数 date:yyyy-MM-dd
	 *
	 * @throws ParseException
	 */
	public static int getTotalDaysOfMonth(String strDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = new GregorianCalendar();

		Date date = null;
		try {
			date = sdf.parse(strDate);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		calendar.setTime(date);
		int month = calendar.get(Calendar.MONTH) + 1; // 月份
		int day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 天数
		return day;
	}

	/***
	 * 获取开始时间与结束时间的相差天数
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static long getDateSubDay(String startDate ,String endDate ) {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat   sdf   =   new   SimpleDateFormat("yyyy-MM-dd");
		long theday = 0;
		try  {
			calendar.setTime(sdf.parse(startDate));
			long   timethis   =   calendar.getTimeInMillis();
			calendar.setTime(sdf.parse(endDate));
			long   timeend   =   calendar.getTimeInMillis();
			theday   =   (timethis   -   timeend)   /   (1000   *   60   *   60   *   24);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return theday;
	}

	public static long getHoursSubDate(String startDate ,String endDate) {

		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat   sdf   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long theday = 0;
		try  {
			calendar.setTime(sdf.parse(startDate));
			long   timethis   =   calendar.getTimeInMillis();
			calendar.setTime(sdf.parse(endDate));
			long   timeend   =   calendar.getTimeInMillis();
			theday   =   (timeend-timethis)   /   (1000   *   60   *   60);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return theday;

	}

	public static long getMinissSubDate(String startDate ,String endDate) {

		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat   sdf   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long theday = 0;
		try  {
			calendar.setTime(sdf.parse(startDate));
			long   timethis   =   calendar.getTimeInMillis();
			calendar.setTime(sdf.parse(endDate));
			long   timeend   =   calendar.getTimeInMillis();
			theday   =   (timeend-timethis)   /   (1000   *   60);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return theday;

	}
	public static long getMinissSubDateFormat(String startDate ,String endDate,String format) {

		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat   sdf   =   new   SimpleDateFormat(format);
		long theday = 0;
		try  {
			calendar.setTime(sdf.parse(startDate));
			long   timethis   =   calendar.getTimeInMillis();
			calendar.setTime(sdf.parse(endDate));
			long   timeend   =   calendar.getTimeInMillis();
			theday   =   (timeend-timethis)   /   (1000   *   60);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return theday;

	}
	/***
	 * 判断日期是否合法
	 * @param date
	 * @return
	 */
	public static boolean  ifIsDateTrueOrFalse(String date) {
		try {
			SimpleDateFormat   sdf   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sdf.setLenient(true);
			sdf.parse(date);
		}catch(Exception e) {
			return  false;
		}
		return true;

	}
	/***
	 * 获取当月天数
	 * @param date
	 * @return
	 */
	public static int getDaysOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}
	/***
	 * 判断日期是否合法
	 * @param date
	 * @return
	 */
	public static boolean  ifIsDateTrueOrFalseFormat(String date,String format) {
		try {
			SimpleDateFormat   sdf   =   new   SimpleDateFormat(format);
			sdf.setLenient(true);
			sdf.parse(date);
		}catch(Exception e) {
			return  false;
		}
		return true;

	}

	/**
	 * 获取起止月份的所有月
	 */
	public static List<String> getBeginAndEndMonth(String y1,String y2){

		try {
			Date startDate = new SimpleDateFormat("yyyy-MM").parse(y1);
			Date endDate = new SimpleDateFormat("yyyy-MM").parse(y2);

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startDate);
			// 获取开始年份和开始月份
			int startYear = calendar.get(Calendar.YEAR);
			int startMonth = calendar.get(Calendar.MONTH);
			// 获取结束年份和结束月份
			calendar.setTime(endDate);
			int endYear = calendar.get(Calendar.YEAR);
			int endMonth = calendar.get(Calendar.MONTH);
			//
			List<String> list = new ArrayList<String>();
			for (int i = startYear; i <= endYear; i++) {
				String date = "";
				if (startYear == endYear) {
					for (int j = startMonth; j <= endMonth; j++) {
						if (j < 9) {
							date = i + "-0" + (j + 1);
						} else {
							date = i + "-" + (j + 1);
						}
						list.add(date);
					}

				} else {
					if (i == startYear) {
						for (int j = startMonth; j < 12; j++) {
							if (j < 9) {
								date = i + "-0" + (j + 1);
							} else {
								date = i + "-" + (j + 1);
							}
							list.add(date);
						}
					} else if (i == endYear) {
						for (int j = 0; j <= endMonth; j++) {
							if (j < 9) {
								date = i + "-0" + (j + 1);
							} else {
								date = i + "-" + (j + 1);
							}
							list.add(date);
						}
					} else {
						for (int j = 0; j < 12; j++) {
							if (j < 9) {
								date = i + "-0" + (j + 1);
							} else {
								date = i + "-" + (j + 1);
							}
							list.add(date);
						}
					}

				}

			}

			// 所有的月份已经准备好
			return list;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getZDMonthLastDate(String month) {

		SimpleDateFormat formatterm = new SimpleDateFormat("yyyy-MM");
		Calendar calendar=null;
		try {
			java.util.Date date =formatterm.parse(month);
			calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MONTH,1);
			calendar.add(Calendar.DAY_OF_YEAR, -1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return formatDate(calendar.getTime());

	}

	/**
	 * 获取当前时间在指定天数后的时间 单位小时
	 * @param day
	 * @return
	 */
	public static String addTime(String newTime,int day){
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date=sdf2.parse(newTime);
			calendar.setTime(date);
			calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + day);
			return sdf2.format(calendar.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取当月的日历
	 * @param yearMonth
	 */
	public static List solarCalender(String years,String months){
		//记录一共有多少天
		int count = 1;
		List<String> list=new ArrayList<>();
		Integer year = Integer.valueOf(years);
		Integer month = Integer.valueOf(months);
		//从1990年到输入的这一年之前一共有多少天
		for (int i = 1990; i < year; i++) {
			if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
				count += 366;
			} else {
				count += 365;
			}
		}
		//看输入的那一年是不是闰年
		boolean bool = false;
		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
			bool = true;
		}
		//看输入的那一年在这个月之前有多少天
		for (int i = 1; i < month; i++) {
			switch (i) {
				case 1:
				case 3:
				case 5:
				case 7:
				case 8:
				case 10:
				case 12:
					count += 31;
					break;
				case 2:
					if (bool)
						count += 29;
					else
						count += 28;
					break;
				default:
					count += 30;
			}
		}

		//记录那个月有多少天
		int day = 0;
		switch (month) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				day = 31;
				break;
			case 2:
				if (bool)
					day = 29;
				else
					day = 28;
				break;
			default:
				day = 30;

		}

		//week记录是周几,周日为0
		int week = count % 7;
		for (int i = 1; i <= day; i++) {
			//每加一天,week加一,当这一周满了以后,就会换行
			if (week == 7) {
				week = 0;
			}
			week++;
			if (months.length()==1){
				months="0"+months;
			}
			int length = (i + "").length();
			if (length==1){
				list.add(years+"-"+months+"-0"+i);
			}else {
				list.add(years+"-"+months+"-"+i);
			}
		}
		return list;
	}

	/**
	 * 获取前几天的日期
	 * @param currentDate
	 */
	public static String downDays(String currentDate,int day){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date date= null;
		try {
			date = formatter.parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, day);
		date = calendar.getTime();
		return formatter.format(date);
	}


   public static void main(String[] args){
	   System.out.println(TimeHelper.addSecond(TimeHelper.getCurrentTime(), -3) );
	   //System.out.println(addTime(TimeHelper.getCurrentHour(),3));
	   System.out.println(validDateStr("2017-01-30"));
//	   List list = solarCalender("2017", "1");
//	   System.out.println(list);
	   int days = getDaysOfMonth(new Date());
	   java.text.SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd");
	   try {
		   System.out.println(getDaysOfMonth(formatter.parse("2022-10-31")));
	   } catch (ParseException e) {
		   e.printStackTrace();
	   }
	   System.out.println(getCurrentYear()+"-"+String.valueOf(Integer.valueOf(getCurrentMonth())-2)+"-01");
	   System.out.println(getCurrentYear()+"-"+getCurrentMonth()+"-"+days);


	   List<String> beginAndEndMonth = getBeginAndEndMonth("2021-10-26", "2022-04-26");
	   System.out.println(beginAndEndMonth);
	   Collections.reverse(beginAndEndMonth);
	   System.out.println(beginAndEndMonth);

	   System.out.println(addTime(getCurrentTime(),3));
	   System.out.println(getCurrentOrder());

	   String currentTime = getCurrentTime();
	   System.out.println(currentTime+"---"+addMinute(currentTime,15));
	   String currentDate = getCurrentDate();
	   System.out.println(currentDate+"---"+downDays(currentDate,-2));
	   System.out.println(currentDate+"---"+addDay(currentDate,-2));
   }
}

随机数生成

 Random r = new Random();
 r.nextInt(); //返回一个随机整数
 r.nextInt(10);	//返回一个10以内的随机整数,不包括10
 r.nextDouble(); //返回一个0~1之间的double类型的随机小数
 r.nextInt(max - min + 1) + min;//取一个范围在[min,max]之间的随机整数

字符串截取

//截取后四位
str.substring(str.length() - 4);
//截取后七位到后四位的字符串
str.substring(str.length() - 7, str.length() - 4);
//将第15-18位的字符串替换位"****"
str.replace(str..substring(14, 18),"****");

String str = "test_https://www.baidu.com/";
//截取_之前字符串
String str1 = str.substring(0, str.indexOf("_"));
//截取_之后字符串
String str1 = str.substring(0, str.indexOf("_"));
String str2 = str.substring(str1.length()+1, str.length());

String str ="0123456_89_sdfdsdsf_23423_auauauau";
//获得第一个点的位置
int index = str.indexOf("_");
//根据第一个点的位置 获得第二个点的位置
index = str.indexOf("_", index + 1);
//根据第二个点的位置,截取 字符串。得到结果 result
String result = str.substring(index + 1);

字符串日期比较

//校验日期("2019-08-07")
//dateFlag=0 说明 endDate 等于 startDate
//dateFlag<0 说明 endDate 小于 startDate
//dateFlag>0 说明 endDate 大于 startDate
int dateFlag = endDate.compareTo(startDate);

//校验时间("16:00")
//timeFlag =0 说明endTime 等于 startTime
//timeFlag <0 说明endTime 小于 startTime
//timeFlag >0 说明endTime 大于 startTime
int timeFlag = endTime.compareTo(startTime);

Double大小比较(保留精度)

Double d1 = 100.0;
Double d2 = 90.0;
Double d3 = 150.005;
Double shengyuNum= 0.1;
int i = 10;
System.out.println(d1.compareTo(d1));  // 0  即=0  d1=d1
System.out.println(d1.compareTo(d2));  // 1  即>0  d1>d2
System.out.println(d1.compareTo(d3));  // -1 即<0  d1<d3
System.out.println(shengyuNum.compareTo(0.0));// 1  即>0

Json解析

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.58</version>
 </dependency>
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

String results="字符串类型的Json";
JSONObject jsonObject = (JSONObject) JSON.parse(results);
Integer code = (Integer) jsonObject.get("code");//解析int类型的字段
String data = jsonObject.get("data").toString();//解析string类型的字段

String deptLists = jsonObject.get("deptList").toString();//解析List类型的字段
JSONArray jsonArray = (JSONArray) JSONArray.parse(deptLists);//将string类型的List转换为数组
for (int i = 0; i < jsonArray.size(); i++) {//遍历数组
	JSONObject object = jsonArray.getJSONObject(i);//将数字下标为i的转换为Object对象
	String deptId = object.getString("deptId");//获取数组中下标为i的对象里面对应的字段值
}

JWT加密解密

	//加密
    public static String signToken(String token){
    	// ss是用来加密数字签名的密钥。
		// ps为加密键值的键
        Algorithm algorithm = Algorithm.HMAC256("ss");
        Map headMap = new HashMap<>();
        headMap.put("ps",token);
        String tokens = JWT.create().withHeader(headMap)
                .withClaim("ps", token)
                .sign(algorithm);
        return tokens;
    }


    /**
     * 先验证token是否被伪造,然后解码token。
     * @param token 字符串token
     * @return 解密后的DecodedJWT对象,可以读取token中的数据。
     */
    public static String deToken( String token) {
        String idNo = null;
        try {
            // 使用了HMAC256加密算法。
            // ss是用来加密数字签名的密钥。
            // ps为加密键值的键
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256("ss")).acceptLeeway(300).build();// Reusable
            // verifier
            // instance
            idNo = verifier.verify(token).getClaim("ps").asString();
        } catch (JWTVerificationException exception) {
            // Invalid signature/claims
            //exception.printStackTrace();
            //logger.info("jwt解密异常");
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            //logger.info("jwt解密异常");
        }
        return idNo;
    }

字符串工具类

	/**
	 * 替换身份证第3-14位为*
	 */
	public static String replaceIdCard(String idCarNo){
		if (idCarNo.length()==18){
			return idCarNo.replace(idCarNo.substring(3, 14), "***********");
		}else {
			return idCarNo;
		}
	}

	/**
	 * 替换手机号第3-7位为*
	 */
	public static String replacePhone(String idCarNo){
		if (idCarNo.length()==11){
			return idCarNo.replace(idCarNo.substring(3, 7), "****");
		}else {
			return idCarNo;
		}
	}

   /**
	 * @param china (字符串 汉字)
	 * @return 汉字转拼音 其它字符不变
	 */
	public static String getPinyin(String china){
		HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
		formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		formart.setVCharType(HanyuPinyinVCharType.WITH_V);
		char[] arrays = china.trim().toCharArray();
		String result = "";
		try {
			for (int i=0;i<arrays.length;i++) {
				char ti = arrays[i];
				if(Character.toString(ti).matches("[\\u4e00-\\u9fa5]")){ //匹配是否是中文
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,formart);
					result += temp[0];
				}else{
					result += ti;
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 两个字符串相乘
	 */
	public static String multiply(String num1, String num2) {
		char[] c1 = num1.toCharArray();
		char[] c2 = num2.toCharArray();
		int[] re=new int[c1.length+c2.length];//re保存计算结果,使用数组防止超出int类型范围
		StringBuilder sb = new StringBuilder();
		for (int i = c1.length-1; i >= 0; i--) {//从个位开始取值计算
			for (int j = c2.length-1; j >=0; j--) {//从个位开始取值计算
				int a=c1[i]-'0';//转化为整数
				int b=c2[j]-'0';//转化为整数
				int r = a * b;//计算结果
				r += re[i + j + 1];//先加上进位的值
				re[i + j + 1] = r % 10;//个位
				re[i + j] += r / 10;//进位
			}

		}
		for (int i = 0; i < re.length; i++) {
			if (re[i]==0&&sb.length()==0){//取出前置位的0
				continue;
			}
			sb.append(re[i]);
		}
		return sb.length()==0?"0":sb.toString();//判断是否为0
	}

    /**
     * 说明:按指定长度分割字符串
     * @param msg
     * @param num
     * @return
     */
    public static String[] splitByNum(String msg, int num) {
      int len = msg.length();
      if (len <= num+1)
        return new String[] {msg};

      int count = len / num;
      count += len > num * count ? 1 : 0;   

      String[] result = new String[count];

      int pos = 0;
      int splitLen = num;
      for (int i = 0; i < count; i++) {
        if (i == count - 1)
          splitLen = len - pos;

        result[i]  = msg.substring(pos,  pos+ splitLen);
        pos += splitLen;

      }

      return result;
  }

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值