JAVA常用工具类汇总

  • 一 : 身份证工具类
  • 二 : 手机号码工具类
  • 三 : 中文拼音工具类
  • 四 : 时间工具类
  • 4.1 : 一个时间段,按月拆分,记录每个月的最大最小时间(用于查询拆分)


一 : 身份证工具类

提供身份证校验器,身份证信息获取方法,身份证号码脱敏方法

package com.utils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * 身份证工具类
 * @author message丶小和尚
 * @create 2020/01/10
 */
public class CardUtil {
    private static final int[] COEFFICIENT_ARRAY = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};// 身份证校验码
    private static final String[] IDENTITY_MANTISSA = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};// 身份证号的尾数规则
    private static final String IDENTITY_PATTERN = "^[0-9]{17}[0-9Xx]$";
    /**
     * 身份证号码验证
     * 1、号码的结构
     * 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。从左至右依次为:六位数字地址码,
     * 八位数字出生日期码,三位数字顺序码和一位数字校验码。
     * 2、地址码(前六位数)
     * 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。
     * 3、出生日期码(第七位至十四位)
     * 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。
     * 4、顺序码(第十五位至十七位)
     * 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,
     * 顺序码的奇数分配给男性,偶数分配给女性。
     * 5、校验码(第十八位数)
     * (1)十七位数字本体码加权求和公式 S = Sum(Ai Wi), i = 0, , 16 ,先对前17位数字的权求和 ;
     * Ai:表示第i位置上的身份证号码数字值; Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
     * (2)计算模 Y = mod(S, 11)
     * (3)通过模( 0 1 2 3 4 5 6 7 8 9 10)得到对应的校验码 Y:1 0 X 9 8 7 6 5 4 3 2
     */
    public static boolean isLegalPattern(String identity) {
        if (identity == null || identity.length() != 18 || !identity.matches(IDENTITY_PATTERN)) {
            return false;
        }
        char[] chars = identity.toCharArray();
        long sum = IntStream.range(0, 17).map(index -> {
            char ch = chars[index];
            int digit = Character.digit(ch, 10);
            int coefficient = COEFFICIENT_ARRAY[index];
            return digit * coefficient;
        }).summaryStatistics().getSum();
        // 计算出的尾数索引
        int mantissaIndex = (int) (sum % 11);
        String mantissa = IDENTITY_MANTISSA[mantissaIndex];
        String lastChar = identity.substring(17);
        return lastChar.equalsIgnoreCase(mantissa);
    }

    /**
     * 通过身份证号码获取 生日,年龄,性别代码
     * @param certificateNo 身份证号码
     * @return Map
     */
    public static Map<String, String> getBirthdayAgeSex(String certificateNo) {
        String birthday = "";
        String age = "";
        String sexCode = "";
        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = certificateNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag) return new HashMap<String, String>();
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && certificateNo.length() == 15) {
            birthday = "19" + certificateNo.substring(6, 8) + "-"
                    + certificateNo.substring(8, 10) + "-"
                    + certificateNo.substring(10, 12);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
        } else if (flag && certificateNo.length() == 18) {
            birthday = certificateNo.substring(6, 10) + "-"
                    + certificateNo.substring(10, 12) + "-"
                    + certificateNo.substring(12, 14);
            sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M";
            age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        if(ValidateUtil.isEmpty(age)){
            map.put("age", "0");
        } else {
            map.put("age", age);
        }
        map.put("sexCode", sexCode);
        return map;
    }

    /**
     * 隐藏身份证某几位
     * @param idCard
     * @return String
     */
    public static String hideIdCard(String idCard){
        return idCard = idCard.replaceAll("(\\d{10})\\d{6}(\\d{2})","$1******$2");
    }
}

二 : 手机号码工具类

提供手机号码格式校验器,手机号码脱敏方法

package com.utils;

import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;

/**
 * 手机号码校验
 * @author message丶小和尚
 * @create 2020/01/10
 */
public class PhoneUtil {

    /**
     * 中国电信号码格式验证 手机段: 133,149,153,173,177,180,181,189,199,1349,1410,1700,1701,1702
     **/
    private static final String CHINA_TELECOM_PATTERN = "(?:^(?:\\+86)?1(?:33|49|53|7[37]|8[019]|99)\\d{8}$)|(?:^(?:\\+86)?1349\\d{7}$)|(?:^(?:\\+86)?1410\\d{7}$)|(?:^(?:\\+86)?170[0-2]\\d{7}$)";

    /**
     * 中国联通号码格式验证 手机段:130,131,132,145,146,155,156,166,171,175,176,185,186,1704,1707,1708,1709
     **/
    private static final String CHINA_UNICOM_PATTERN = "(?:^(?:\\+86)?1(?:3[0-2]|4[56]|5[56]|66|7[156]|8[56])\\d{8}$)|(?:^(?:\\+86)?170[47-9]\\d{7}$)";

    /**
     * 中国移动号码格式验证
     * 手机段:134,135,136,137,138,139,147,148,150,151,152,157,158,159,178,182,183,184,187,188,198,1440,1703,1705,1706
     **/
    private static final String CHINA_MOBILE_PATTERN = "(?:^(?:\\+86)?1(?:3[4-9]|4[78]|5[0-27-9]|78|8[2-478]|98)\\d{8}$)|(?:^(?:\\+86)?1440\\d{7}$)|(?:^(?:\\+86)?170[356]\\d{7}$)";

    /**
     * 中国大陆手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            if (checkChinaMobile(phone) || checkChinaUnicom(phone) || checkChinaTelecom(phone)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 中国移动手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkChinaMobile(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            Pattern regexp = Pattern.compile(CHINA_MOBILE_PATTERN);
            if (regexp.matcher(phone).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 中国联通手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkChinaUnicom(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            Pattern regexp = Pattern.compile(CHINA_UNICOM_PATTERN);
            if (regexp.matcher(phone).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 中国电信手机号码校验
     * @param phone
     * @return
     */
    public static boolean checkChinaTelecom(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            Pattern regexp = Pattern.compile(CHINA_TELECOM_PATTERN);
            if (regexp.matcher(phone).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 隐藏手机号中间四位
     * @param phone
     * @return String
     */
    public static String hideMiddleMobile(String phone) {
        if (StringUtils.isNotBlank(phone)) {
            phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
        return phone;
    }

    /*public static void main(String[] args) {
        log.debug(checkPhone("15600000001"));
        log.debug(hideMiddleMobile("15600000001"));
    }*/

}

三 : 中文拼音工具类

提供获取中文所有汉字首字母,中文首汉字首字母等方法

package com.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 中文拼音工具类
 * @author message丶小和尚
 * @create 2020/01/10
 */
public class PinyinUtil {

    /**
     * 获取第一个汉字的首字母
     * @param string
     * @return
     */
    public static String getPinYinFirstChar(String string) {
        if(ValidateUtil.isEmpty(string)){
            return "";
        }
        return getPinYinHeadChar(string).substring(0,1);
    }

    /**
     * 获取所有汉字首字母
     * @param string
     * @return
     */
    public static String getPinYinHeadChar(String string) {
        StringBuilder convert = new StringBuilder();
        for (int j = 0; j < string.length(); j++) {
            char word = string.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        return convert.toString().toUpperCase().substring(0,1);
    }

    /**
     * 获取汉字的所有大写拼音 eg:NANJINGSHI
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getAllUpperCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//设置大写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//匹配中文,非中文转换会转换成null
                String[] pinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c,defaultFormat);
                pinyin.append(pinyinStringArray[0]);
            } else {
                pinyin.append(c);
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字的所有小写拼音 eg:nanjingshi
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getAllLowerCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//设置大写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {//匹配中文,非中文转换会转换成null
                String[] pinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c,defaultFormat);
                pinyin.append(pinyinStringArray[0]);
            } else {
                pinyin.append(c);
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字的所有首字母大写拼音 eg:NJS
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getUpperCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);//设置大小写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){//匹配中文,非中文转换会转换成null
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (hanyuPinyinStringArray != null) {
                    pinyin.append(hanyuPinyinStringArray[0].charAt(0));
                }
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字的所有首字母小写拼音 eg:njs
     * @param name
     * @return
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String getLowerCaseChinese(String name) throws BadHanyuPinyinOutputFormatCombination {
        char[] charArray = name.toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);//设置大小写格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//设置声调格式
        for(char c:charArray){//匹配中文,非中文转换会转换成null
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
                if (hanyuPinyinStringArray != null) {
                    pinyin.append(hanyuPinyinStringArray[0].charAt(0));
                }
            }
        }
        return pinyin.toString();
    }
}

四 : 时间工具类

提供时间,字符串转换.时间间隔计算,最大时间,最小时间等

package com.utils;

import com.chang.util.ValidateUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 * @author message丶小和尚
 * @create 2020/01/10
 */
public class DateUtil {

    public static String YEAR = "yyyy";
    public static String YEARMONTH = "yyyy-MM";
    public static String YEARMONTHDAY = "yyyy-MM-dd";
    public static String YEARMONTHDAYTIMEBRANCH = "yyyy-MM-dd HH:mm";
    public static String YEARMONTHDAYTIMEBRANCHSECOND = "yyyy-MM-dd HH:mm:ss";
    public static String YEARMONTHDAYTIMEBRANCHSECONDMILLISECOND = "yyyy-MM-dd HH:mm:ss SSS";
    private static long differDay = 1000 * 24 * 60 * 60;
    private static long differHour = 1000 * 60 * 60;
    private static long differMinute = 1000 * 60;
    private static long differSecond = 1000;
    public static String DIFFERTIME = "0分钟";

    /**
     * 获取当前时间戳 yyyy-MM-dd HH:mm:ss
     * @return String
     */
    public static String getCurrentTime(){
        return DateFormatUtils.format(new Date(),YEARMONTHDAYTIMEBRANCHSECOND);
    }

    /**
     * 获取年
     * @return String
     */
    public static String getYear(Date date){
        return DateFormatUtils.format(date,YEAR);
    }

    /**
     * 获取年月
     * @return String
     */
    public static String getYearMonth(Date date){
        return DateFormatUtils.format(date,YEARMONTH);
    }

    /**
     * 获取年月日
     * @return String
     */
    public static String getYearMonthDay(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAY);
    }

    /**
     * 获取年月日
     * @return String
     */
    public static String getYearMonthDayForResult(Date date){
        return DateFormatUtils.format(date,"yyyy年MM月dd日");
    }

    /**
     * 获取年月日时分
     * @return String
     */
    public static String getYearMonthDayTimeBranch(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCH);
    }

    /**
     * 获取年月日时分秒
     * @return String
     */
    public static String getYearMonthDayTimeBranchSecond(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCHSECOND);
    }

    /**
     * 获取当月日时分秒毫秒
     * @return String
     */
    public static String getYearMonthDayTimeBranchSecondMillisecond(Date date){
        return DateFormatUtils.format(date,YEARMONTHDAYTIMEBRANCHSECONDMILLISECOND);
    }

    /**
     * 将时间转换成固定格式字符串
     * @param date 时间
     * @param pattern 时间格式
     * @return String
     */
    public static String getStringByDate(Date date,String pattern) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime localDateTime = dateToDateTime(date);
        return formatter.format(localDateTime);
    }

    /**
     * 将字符串转换成固定格式时间 yyyy-MM-dd
     * @param string 时间字符串
     * @return Date
     */
    public static Date getDateByString(String string) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(string, dateTimeFormatter);
        return localDateToDate(localDate);
    }

    /**
     * 将字符串转换成固定格式时间 yyyy-MM-dd HH:mm:ss
     * @param string 时间字符串
     * @return Date
     */
    public static Date getDateTimeByString(String string) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(string, dateTimeFormatter);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取某天最小时间
     * @param date 时间
     * @return Date
     */
    public static Date getDateMinTime(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(LocalTime.MIN);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取某天最大时间
     * @param date 时间
     * @return Date
     */
    public static Date getDateMaxTime(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(LocalTime.MAX);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期之后的某一天时间
     * @param date 时间
     * @param days 天数
     * @return Date
     */
    public static Date getAfterDaysDateTime(Date date, int days) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.plusDays(days);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期之前的某一天时间
     * @param date 时间
     * @param days 天数
     * @return Date
     */
    public static Date getBeforeDaysDateTime(Date date, int days) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.minusDays(days);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期月份第一天 00:00:00 000
     * @param date 时间
     * @return Date
     */
    public static Date getFirstDayOfMonth(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 获取日期月份最后一天 23:59:59 999
     * @param date 时间
     * @return Date
     */
    public static Date getLastDayOfMonth(Date date) {
        LocalDateTime localDateTime = dateToDateTime(date);
        localDateTime = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
        return dateTimeToDate(localDateTime);
    }

    /**
     * 两个日期相差多少个月
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilMonthByTwoDate(Date dateBefore, Date dateAfter) {
        LocalDate localDate1 = dateToLocalDate(dateBefore);
        LocalDate localDate2 = dateToLocalDate(dateAfter);
        return ChronoUnit.MONTHS.between(localDate1, localDate2);
    }

    /**
     * 两个日期相差多少天
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilDayByTwoDate(Date dateBefore, Date dateAfter) {
        LocalDate localDate1 = dateToLocalDate(dateBefore);
        LocalDate localDate2 = dateToLocalDate(dateAfter);
        return ChronoUnit.DAYS.between(localDate1, localDate2);
    }

    /**
     * 两个日期相差多少小时
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilHoursByTwoDate(Date dateBefore, Date dateAfter) {
        LocalDateTime localDate1 = dateToDateTime(dateBefore);
        LocalDateTime localDate2 = dateToDateTime(dateAfter);
        Long second = Duration.between(localDate1, localDate2).get(ChronoUnit.SECONDS);
        return second / 3600;
    }

    /**
     * 两个日期相差多少秒
     * @param dateBefore 开始时间
     * @param dateAfter 结束时间
     * @return Long
     */
    public static Long getUntilHoursByTwoSecond(Date dateBefore, Date dateAfter) {
        LocalDateTime localDate1 = dateToDateTime(dateBefore);
        LocalDateTime localDate2 = dateToDateTime(dateAfter);
        return Duration.between(localDate1, localDate2).get(ChronoUnit.SECONDS);
    }

    /**
     * LocalDateTime转换为Date
     * @param localDateTime 时间
     * @return Date
     */
    public static Date dateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date转换为LocalDateTime
     * @param date 时间
     * @return LocalDateTime
     */
    public static LocalDateTime dateToDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * Date转换为LocalDate
     * @param date 时间
     * @return LocalDate
     */
    public static LocalDate dateToLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * LocalDate转换为Date
     * @param localDate 时间
     * @return Date
     */
    public static Date localDateToDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取增加天数后的日期
     * @param date 时间
     * @param days 天数
     * @return Date
     */
    public static Date getAddDay(Date date,Integer days){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        return calendar.getTime();
    }

    /**
     * 获取当前时间
     * @return Date
     */
    public static Date getCurDate() {
        return new Date();
    }

    /**
     * 获取两个时间相差时间
     * @param beforeDate 之前的时间
     * @param endDate 之后的时间
     * @return String
     */
    public static String getStringDateInfoByTwoDate(Date beforeDate,Date endDate) {
        long diff = endDate.getTime() - beforeDate.getTime();//获得两个时间的毫秒时间差异
        long day = diff / differDay;//计算差多少天
        long hour = diff % differDay / differHour;//计算差多少小时
        long min = diff % differDay % differHour / differMinute;//计算差多少分钟
        long second = diff % differDay % differHour % differMinute / differSecond;//计算差多少秒
        String string = "";
        if(0 != day){
            string = string + day + "天";
        }
        if(0 != hour){
            string = string + hour + "小时";
        }
        if(0 != min){
            string = string + min + "分钟";
        }
        if(ValidateUtil.isEmpty(string) && second > 0){//差距小于一分钟,计算秒
            string = second + "秒";
        }
        if(ValidateUtil.isEmpty(string)){//没有差距则为0分钟
            string = DIFFERTIME;
        }
        return string;
    }

    /**
     * 获取给定年月的最大最小日期
     * @param string yyyy-MM
     * @param flag true 最小日期 false 最大日期
     * @return String
     */
    public static String getMonthDayOneAndLast(String string,boolean flag){
        Integer year = Integer.parseInt(string.split("-")[0]);
        Integer month = Integer.parseInt(string.split("-")[1]);
        if(flag){
            return DateUtil.getDayByFlagOfMonth(year, month, true);
        }
        return DateUtil.getDayByFlagOfMonth(year, month, false);
    }

    /**
     * 获取给定年月的第一天和最后一天
     * @param year 年
     * @param month 月
     * @param flag true 第一天,false 最后一天
     * @return String
     */
    public static String getDayByFlagOfMonth(int year,int month,boolean flag){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);//设置年份
        calendar.set(Calendar.MONTH, month - 1);//设置月份
        if(flag){
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));//设置日历中月份的天数
        } else {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));//设置日历中月份的天数
        }
        return getYearMonthDay(calendar.getTime());//格式化日期
    }

    /**
     * 计算传入时间是否超时
     * @param longDate 传入时间
     * @param intervalTime 规定时间 秒
     * @return boolean
     */
    public static boolean isTimeOut(Long longDate,Long intervalTime){
        return new Date(System.currentTimeMillis()).getTime() - new Date(longDate).getTime() / 1000 > intervalTime;
    }

}
4.1 : 一个时间段,按月拆分,记录每个月的最大最小时间(用于查询拆分)

定义基础类

package utils;

import lombok.Data;

@Data
public class DateMonthDay {

    private String month;
    private String beginDay;
    private String endDay;

    public DateMonthDay() {

    }

    public DateMonthDay(String month, String beginDay, String endDay) {
        this.month = month;
        this.beginDay = beginDay;
        this.endDay = endDay;
    }

}

工具类

package utils;

@Data
public class DateUtil {

    public static List<DateMonthDay> getMonthFirstEndDateByDate(Date startDate, Date endDate){
        List<DateMonthDay> dataList = new ArrayList<>();
        String startYearMonth = getYearMonth(startDate);
        String endYearMonth = getYearMonth(endDate);
        if(null == endYearMonth) return dataList;
        //校验时间前后
        if(compareToDateTime(startDate, endDate)) return dataList;
        //时间拆分月
        Long differMonth = getUntilMonthByTwoDate(startDate, endDate);
        if(0L == differMonth){
            dataList.add(new DateMonthDay(startYearMonth, getYearMonthDay(startDate), getYearMonthDay(endDate)));
        } else {
            for(int i = 0; i <= differMonth.intValue(); i ++){
                Date currentDate = getAfterMonthDate(startDate, i);
                if(endYearMonth.equals(getYearMonth(currentDate))){
                    dataList.add(new DateMonthDay(endYearMonth, getYearMonthDay(getFirstDayOfMonth(currentDate)),
                            getYearMonthDay(endDate)));
                    break;
                } else {
                    if(i == 0){
                        dataList.add(new DateMonthDay(startYearMonth, getYearMonthDay(startDate),
                                getYearMonthDay(getLastDayOfMonth(startDate))));
                    } else {
                        dataList.add(new DateMonthDay(getYearMonth(currentDate),
                                getYearMonthDay(getFirstDayOfMonth(currentDate)), getYearMonthDay(getLastDayOfMonth(currentDate))));
                    }
                }
            }
        }
        return dataList;
    }

}