Java日期工具类的封装详解

在日常的开发中,我们难免会对日期格式化,对日期进行计算,对日期进行校验,为了避免重复写这些琐碎的逻辑,我这里封装了一个日期工具类,方便以后使用,直接复制代码到项目中即可使用,需要的可以参考一下

概述

在日常的开发中,我们难免会对日期格式化,对日期进行计算,对日期进行校验,为了避免重复写这些琐碎的逻辑,我这里封装了一个日期工具类,方便以后使用,直接复制代码到项目中即可使用。

日期工具类代码:

import org.apache.commons.lang3.StringUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 常用日期工具类
 *
 * @author compass
 * @date 2022/10/21 14:20
 * @since 1.0.0
 **/
public class DateTools {
    public final static String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    public final static String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public final static String DEFAULT_DATE_FORMAT_SHORT = "yyMMdd";
    public final static String DEFAULT_YEAR_MODTH_SHORT = "yyyyMM";
    public final static String DEFAULT_TIME_FORMAT_SHORT = "HHmmss";
    public final static String DEFAULT_DATETIME_FORMAT_SHORT = "yyMMddHHmmss";
    public final static String DEFAULT_DATE_FORMAT_ALLSHORT = "yyyyMMdd";

    public static final String SIMPLE_DATE_STR = "yyyy-MM-dd";
    public static final String FULL_DATE_STR = "yyyy-MM-dd HH:mm:ss";
    public static final String ALL_FULL_DATE_STR = "yyyy-MM-dd HH:mm:ss.S";
    public static final String PART_DATE_STR = "yyyy-MM-dd HH:mm";
    public static final String DATEFORMAT_Y2H = "yyyy-MM-dd HH";

    public static final String SIMPLE_RULE_DATE_STR = "yyyy/MM/dd";
    public static final String FULL_RULE_DATE_STR = "yyyy/MM/dd HH:mm:ss";
    public static final String PART_RULE_DATE_STR = "yyyy/MM/dd HH:mm";
    public static final String SMALL_PART_RULE_DATE_STR = "HH:mm";

    public static final String DATE_FORMAT_YYYYMMDD = "yyyyMMdd";
    public static final String DATE_FORMAT_YYYYMMDDHH = "yyyyMMddHH";
    public static final String DATE_FORMAT_YYYYMMDDHHMM = "yyyyMMddHHmm";
    public static final String DATE_FORMAT_YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static final String SIMPLE_POINT_DATE_STR = "yyyy.MM.dd";
    public static final String FULL_POINT_DATE_STR = "yyyy.MM.dd HH:mm:ss";

    /**
     * 锁对象
     */
    private static final Object lockObj = new Object();

    /**
     * 存放不同格式的线程安全的SimpleDateFormat
     */
    private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<>();

    public enum DateType {
        YEAR("YEAR", 1),
        MONTH("MONTH", 2),
        DAY("DAY", 3),
        HOUR("HOUR", 4),
        MINUTE("MINUTE", 5),
        SECOND("SECOND", 6);

        private String name;
        private int value;

        DateType(String name, int value) {
            this.value = value;
            this.name = name;
        }

        public int getValue() {
            return value;
        }

        public String getName() {
            return name;
        }
    }

    /**
     * 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
     *
     * @param pattern
     * @return
     */
    private static SimpleDateFormat getSdf(final String pattern) {
        ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
        if (tl == null) {
            synchronized (lockObj) {
                tl = sdfMap.get(pattern);
                if (tl == null) {
                    tl = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
                    sdfMap.put(pattern, tl);
                }
            }
        }
        return tl.get();
    }

    private static String[] supportFmt = new String[]{ALL_FULL_DATE_STR, SIMPLE_DATE_STR,DATE_FORMAT_YYYYMMDDHHMMSS, DEFAULT_YEAR_MODTH_SHORT, DEFAULT_TIME_FORMAT, DEFAULT_DATE_FORMAT_SHORT};

    private static String checkFmt(String datestr) {
        if (datestr == null)
            return null;
        int len = datestr.length();
        if (len == 0)
            return null;
        String fmt;
        switch (len) {
            case 19:
                fmt = supportFmt[0];
                break;
            case 10:
                fmt = supportFmt[1];
                break;
            case 14:
                fmt = supportFmt[2];
                break;
            case 6:
                fmt = supportFmt[3];
                break;
            case 8: {
                if (datestr.indexOf(":") > 0) {
                    fmt = supportFmt[4];
                } else {
                    fmt = supportFmt[5];
                }
            }
            break;
            default:
                return null;
        }
        return fmt;
    }

    /**
     * 日期格式,正则表达式
     */
    private static String[] supportFmtPattern = new String[]{
            "\\d{4}\\-\\d{1,2}\\-\\d{1,2}", "yyyy-MM-dd",
            "\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy-MM-dd HH:mm:ss",
            "\\d{1,2}:\\d{1,2}:\\d{1,2}", "HH:mm:ss",
            "\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}", "HH:mm:ss.SSS",
            "\\d{4}年\\d{1,2}月\\d{1,2}日", "yyyy年MM月dd日",
            "\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}", "yyyy-MM-dd HH:mm:ss.SSS",
            "\\d{4}(10|11|12|0[1-9])(30|31|[1-2][0-9]|0[1-9])(20|21|22|23|1[0-9]|0[0-9])([1-5][0-9]|0[0-9])([1-5][0-9]|0[0-9])", "yyyyMMddHHmmss",
            "\\d{4}(10|11|12|0[1-9])(30|31|[1-2][0-9]|0[1-9])", "yyyyMMdd",
            "\\d{4}(10|11|12|0[1-9])(30|31|[1-2][0-9]|0[1-9])(20|21|22|23|1[0-9]|0[0-9])([1-5][0-9]|0[0-9])([1-5][0-9]|0[0-9])\\d{1,3}", "yyyyMMddHHmmssSSS",
            "\\d{4}(10|11|12|0[1-9])", "yyyyMM",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}", "yyyy/MM/dd",
            "\\d{4}\\.\\d{1,2}\\.\\d{1,2}", "yyyy.MM.dd",
            "\\d{1,2}\\-\\d{1,2}\\-\\d{4}", "MM-dd-yyyy",
            "\\d{1,2}\\/\\d{1,2}\\/\\d{4}", "MM/dd/yyyy",
            "\\d{1,2}\\/\\d{1,2}\\/\\d{2}", "MM/dd/yy",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy/MM/dd'T'HH:mm:ss",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy/MM/dd't'HH:mm:ss",
            "\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy-MM-dd'T'HH:mm:ss",
            "\\d{4}-\\d{1,2}-\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy-MM-dd't'HH:mm:ss",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}Z", "yyyy/MM/dd'T'HH:mm:ss.SSS'Z'",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}z", "yyyy/MM/dd't'HH:mm:ss.SSS'z'",
            "\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "\\d{4}-\\d{1,2}-\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}z", "yyyy-MM-dd't'HH:mm:ss.SSS'z'"
    };

    /**
     * 日期格式,正则表达式
     */
    private static String[] supportDateFmtPattern = new String[]{
            "\\d{4}\\-\\d{1,2}\\-\\d{1,2}", "yyyy-MM-dd",
            "\\d{4}年\\d{1,2}月\\d{1,2}日", "yyyy年MM月dd日",
            "\\d{4}(10|11|12|0[1-9])(30|31|[1-2][0-9]|0[1-9])", "yyyyMMdd",
            "\\d{4}(10|11|12|0[1-9])", "yyyyMM",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}", "yyyy/MM/dd",
            "\\d{4}\\.\\d{1,2}\\.\\d{1,2}", "yyyy.MM.dd",
            "\\d{1,2}\\-\\d{1,2}\\-\\d{4}", "MM-dd-yyyy",
            "\\d{1,2}\\/\\d{1,2}\\/\\d{4}", "MM/dd/yyyy",
            "\\d{1,2}\\/\\d{1,2}\\/\\d{2}", "MM/dd/yy"
    };

    /**
     * 时间格式,正则表达式
     */
    private static String[] supportTimeFmtPattern = new String[]{
            "\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy-MM-dd HH:mm:ss",
            "\\d{1,2}:\\d{1,2}:\\d{1,2}", "HH:mm:ss",
            "\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}", "HH:mm:ss.SSS",
            "\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}", "yyyy-MM-dd HH:mm:ss.SSS",
            "\\d{4}(10|11|12|0[1-9])(30|31|[1-2][0-9]|0[1-9])(20|21|22|23|1[0-9]|0[0-9])([1-5][0-9]|0[0-9])([1-5][0-9]|0[0-9])", "yyyyMMddHHmmss",
            "\\d{4}(10|11|12|0[1-9])(30|31|[1-2][0-9]|0[1-9])(20|21|22|23|1[0-9]|0[0-9])([1-5][0-9]|0[0-9])([1-5][0-9]|0[0-9])\\d{1,3}", "yyyyMMddHHmmssSSS",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy/MM/dd'T'HH:mm:ss",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy/MM/dd't'HH:mm:ss",
            "\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy-MM-dd'T'HH:mm:ss",
            "\\d{4}-\\d{1,2}-\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}", "yyyy-MM-dd't'HH:mm:ss",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}Z", "yyyy/MM/dd'T'HH:mm:ss.SSS'Z'",
            "\\d{4}\\/\\d{1,2}\\/\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}z", "yyyy/MM/dd't'HH:mm:ss.SSS'z'",
            "\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "\\d{4}-\\d{1,2}-\\d{1,2}t\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}z", "yyyy-MM-dd't'HH:mm:ss.SSS'z'"
    };


    /**
     * 根据日期时间串推断日期格式
     *
     * @param datestr 日期字符串
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String checkFmtByPattern(String datestr) {
        if (datestr == null)
            return null;
        for (int i = 0; i < supportFmtPattern.length; i += 2) {
            if (Pattern.matches(supportFmtPattern[i], datestr)) {
                return supportFmtPattern[i + 1];
            }
        }
        return null;
    }

    /**
     * 根据字符串格式自动判断日期格式,支持11种  <br>
     * yyyy-MM-dd HH:mm:ss.SSS <br>
     * yyyy-MM-dd HH:mm:ss <br>
     * yyyy-MM-dd <br>
     * yyyy.MM.dd <br>
     * yyyy/MM/dd <br>
     * HH:mm:ss.SSS <br>
     * HH:mm:ss <br>
     * yyyyMMdd <br>
     * yyyyMMddHHmmssSSS <br>
     * yyyyMMddHHmmss <br>
     * yyyyMM <br>
     *
     * @param datestr
     * @return
     */
    public static Date parse(String datestr) {
        String fmt = checkFmtByPattern(datestr);
        return parse(datestr, fmt);
    }


    /**
     * 获取yyyy-MM-dd日期类型
     *
     * @param dateStr 日期字符串
     * @param fmt     日期格式
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Date parse(String dateStr, String fmt) {
        try {
            return getSdf(fmt).parse(dateStr);
        } catch (NullPointerException | ParseException e) {
            throw new RuntimeException(String.format("不支持的时间格式,[%s]", dateStr));
        }

    }

    /**
     * 获取yyyy-MM-dd日期类型
     *
     * @param datestr 日期字符串
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Date parseDay(String datestr) {
        try {
            return getSdf(supportFmt[1]).parse(datestr);
        } catch (ParseException e) {
            throw new RuntimeException("不支持的时间格式");
        }
    }


    /**
     * 获取yyyy-MM-dd HH:mm:ss日期类型
     *
     * @param datestr 日期字符串
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Date parseDayTime(String datestr) {
        try {
            return getSdf(supportFmt[0]).parse(datestr);
        } catch (ParseException e) {
            throw new RuntimeException("不支持的时间格式");
        }
    }


    /**
     * 将日期格式化成指定格式
     *
     * @param dt 日期
     * @param dt 格式字符串
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String format(Date dt, String... pattern) {
        if (pattern != null && pattern.length > 1) {
            throw new RuntimeException("日期格式字符串,只支持一个");
        }
        String format = pattern.length <= 0 ?DEFAULT_DATETIME_FORMAT : pattern[0];
        return getSdf(format).format(dt);
    }


    /**
     * 将日期格式化为yyyy-MM-dd HH:mm:ss
     *
     * @param dt 日期
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String formatDayTime(Date dt) {
        return getSdf(supportFmt[0]).format(dt);
    }


    /**
     * 将日期格式化为yyyy-MM-dd
     *
     * @param dt 开日期
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String formatDay(Date dt) {
        return getSdf(supportFmt[1]).format(dt);
    }


    /**
     * 将日期格式化为HH:mm:ss
     *
     * @param dt 开日期
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String formatTime(Date dt) {
        return getSdf(supportFmt[4]).format(dt);
    }


    /**
     * 计算月份差[日期型],按月份计算忽略天数
     *
     * @param fromDate 开始日期
     * @param toDate   结束日期
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Integer monthBetween(Date fromDate, Date toDate) {

        if ((fromDate == null) || (toDate == null)) {
            return null;
        }
        int times = 1;
        if (!fromDate.after(toDate)) {
            Calendar calFrom = Calendar.getInstance();
            Calendar calTo = Calendar.getInstance();
            calFrom.setTime(fromDate);
            calFrom.set(Calendar.DAY_OF_MONTH, 1);
            calTo.setTime(toDate);
            calTo.set(Calendar.DAY_OF_MONTH, 1);
            while (calFrom.before(calTo)) {
                calFrom.add(2, 1);
                times++;
            }
        } else {
            return 0;
        }
        return times;

    }


    /**
     * 计算月份差(字符型),自动判定格式
     *
     * @param fromDate 开始日期
     * @param toDate   结束日期
     * @return java.lang.Integer
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Integer monthBetween(String fromDate, String toDate) {

        if ((fromDate == null) || (toDate == null)) {
            return null;
        }
        return monthBetween(parse(fromDate), parse(toDate));

    }

    /**
     * 计算天数差
     *
     * @param from 开始日期
     * @param end  结束日期
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Integer daysBetween(Date from, Date end) {
        if ((from == null) || (end == null)) {
            return null;
        }
        long fromL = from.getTime();
        long endL = end.getTime();
        double diff = (endL - fromL) / 86400000L;
        return new Integer(new Double(Math.ceil(diff)).intValue());
    }


    /**
     * 计算天数差
     *
     * @param from 开始日期
     * @param end  结束日期
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Integer dayBetween(String from, String end) {
        if ((from == null) || (end == null)) {
            return null;
        }
        return daysBetween(parse(from), parse(end));
    }


    /**
     * 日期年月加减 +天
     *
     * @param date 日期
     * @param adds 天数
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Date addDay(Date date, int adds) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, adds);
        return cal.getTime();
    }

    /**
     * 日期字符串年月加减 +天
     *
     * @param date 日期字符串
     * @param adds 天数
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String addDay(String date, int adds) {
        String fmt = checkFmtByPattern(date);
        Date r = addDay(parse(date), adds);
        return format(r, fmt);
    }

    /**
     * 日期年月加减 +月
     *
     * @param date 日期
     * @param adds 天数
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Date addMonth(Date date, int adds) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, adds);
        return cal.getTime();
    }

    /**
     * 日期年月加减 +月
     *
     * @param date 日期字符串
     * @param adds 天数
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String addMonth(String date, int adds) {
        String fmt = checkFmtByPattern(date);
        Date r = addMonth(parse(date), adds);
        return format(r, fmt);
    }

    /**
     * 日期年月加减 +年
     *
     * @param date 日期
     * @param adds 天数
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static Date addYear(Date date, int adds) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.YEAR, adds);
        return cal.getTime();
    }

    /**
     * 日期年月加减 +年
     *
     * @param date 日期字符串
     * @param adds 天数
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:06
     * @since 1.0.0
     **/
    public static String addYear(String date, int adds) {
        String fmt = checkFmtByPattern(date);
        Date r = addYear(parse(date), adds);
        return format(r, fmt);
    }

    /**
     * 返回当前日期
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 返回当前日期字符串
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static String getNowStr(String format) {
        return getSdf(format).format(new Date());
    }

    /**
     * 返回当前年
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static int getNowYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回当前月
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static int getNowMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH);
    }

    /**
     * 获取今天是多少号
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static int getNowDay() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 返回当前日期是今年的第几天
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static int getNowDayOfYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * 获取今天是星期几
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 11:10
     * @since 1.0.0
     **/
    public static int getNowDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_WEEK) - 1;
    }

    /**
     * 获取日期字符串的某一个时间单位
     *
     * @param dateStr 日期字符串
     * @param format  日期格式化模式 默认:yyyy/MM/dd
     * @param unit    获取的日期单位
     * @return int
     * @author compass
     * @date 2022/9/14
     * @since 1.0.0
     **/
    public static int getDateUnit(String dateStr, String format, DateTools.DateType unit) {
        int type = unit.getValue();
        format = StringUtils.isNotBlank(format) ? format : DEFAULT_DATETIME_FORMAT;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar startCalendar = Calendar.getInstance();
        Date dateTime = null;
        try {
            dateTime = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式错误");

        }
        startCalendar.setTime(dateTime);
        int year = startCalendar.get(Calendar.YEAR);
        int month = startCalendar.get(Calendar.MONTH) + 1;
        int day = startCalendar.get(Calendar.DAY_OF_MONTH);
        int hour = startCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = startCalendar.get(Calendar.MINUTE);
        int second = startCalendar.get(Calendar.SECOND);
        switch (type) {
            case 1:
                return year;
            case 2:
                return month;
            case 3:
                return day;
            case 4:
                return hour;
            case 5:
                return minute;
            case 6:
                return second;

            default:
                throw new RuntimeException("日期单位不正确");
        }
    }

    /**
     * 计算距离生日还有多少天
     *
     * @param date:生日日期
     * @param format:日期格式 默认:yyyy-MM-dd
     */
    public static int getBirthDay(String date, String... format) {
        if (format != null && format.length > 1) {
            throw new RuntimeException("日期格式字符串,只支持一个");
        }
        int days = 0;
        try {
            SimpleDateFormat myFormatter = new SimpleDateFormat(format.length <= 0 ? "yyyy-MM-dd" : format[0]);
            String cliDate = date;
            Calendar cToday = Calendar.getInstance(); // 存今天
            Calendar cBirth = Calendar.getInstance(); // 存生日
            cBirth.setTime(myFormatter.parse(cliDate)); // 设置生日
            cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR)); // 修改为本年
            if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
                // 生日已经过了,要算明年的了
                days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
                days += cBirth.get(Calendar.DAY_OF_YEAR);
            } else {
                // 生日还没过
                days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 获取服务器启动时间
     *
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 14:40
     * @since 1.0.0
     **/
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 获取服务器启动时间
     *
     * @param format 日期格式 默认 yyyy-MM-dd HH:mm:ss
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 14:40
     * @since 1.0.0
     **/
    public static String getServerStartDateFormat(String... format) {
        if (format != null && format.length > 1) {
            throw new RuntimeException("日期格式字符串,只支持一个");
        }
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return format(new Date(time), format.length <= 0 ? DEFAULT_DATETIME_FORMAT : format[0]);

    }

    /**
     * 格式化时间
     *
     * @param sec 秒
     * @return java.lang.String
     * @author compass
     * @date 2022/10/21 14:46
     * @since 1.0.0
     **/
    private static String NumFormat(long sec) {
        if (String.valueOf(sec).length() < 2) {
            return "0" + sec;
        } else {
            return String.valueOf(sec);
        }
    }


    /**
     * 秒转小时分
     *
     * @param second 秒
     * @return java.lang.String
     * @author compass
     * @date 2022/10/21 14:46
     * @since 1.0.0
     **/
    public static String getFormatTime(Long second) {

        if (second != null) {

            if (second < 3600) {//分

                return NumFormat(second / 60) + "分";
            }

            if (second < 3600 * 24) {//时

                return NumFormat(second / 60 / 60) + "小时" + NumFormat(second / 60 % 60) + "分";
            }

            if (second >= 3600 * 24) {//天

                return NumFormat(second / 60 / 60 / 24) + "天" + NumFormat(second / 60 / 60 % 24) + "小时" + NumFormat(second / 60 % 60) + "分";
            }
        }

        return "--";
    }


    /**
     * 获取当前时间前面某天或者后面某天
     *
     * @param date   日期
     * @param amount 相隔天数,正数表示未来日期,负数表示过去日期
     * @return java.util.Date
     * @author compass
     * @date 2022/10/21 14:49
     * @since 1.0.0
     **/
    public static Date getOtherDay(Date date, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, amount);
        Date time = calendar.getTime();
        return time;
    }

    /**
     * 获取周几
     *
     * @param date
     * @return
     */
    public static String getWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        String week = null;
        if (weekday == 1) {
            week = "星期天";
        } else if (weekday == 2) {
            week = "星期一";
        } else if (weekday == 3) {
            week = "星期二";
        } else if (weekday == 4) {
            week = "星期三";
        } else if (weekday == 5) {
            week = "星期四";
        } else if (weekday == 6) {
            week = "星期五";
        } else if (weekday == 7) {
            week = "星期六";
        }
        return week;
    }

    /**
     * 判断是不是本周
     *
     * @param date 日期
     * @return boolean
     * @author compass
     * @date 2022/10/21 14:54
     * @since 1.0.0
     **/
    public static boolean isThisWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        calendar.setTime(date);
        int dateWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        if (currentWeek == dateWeek) {
            return true;
        }
        return false;
    }

    /**
     * 判断是不是本周
     *
     * @param date   日期
     * @param format 日期格式字符
     * @return boolean
     * @author compass
     * @date 2022/10/21 14:54
     * @since 1.0.0
     **/
    public static boolean isThisWeek(String date, String format) {
        Calendar calendar = Calendar.getInstance();
        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        calendar.setTime(parse(date, format));
        int dateWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        if (currentWeek == dateWeek) {
            return true;
        }
        return false;
    }

    /**
     * 判断当前时间
     *
     * @param date   日期
     * @param format 日期格式
     * @return boolean
     * @author compass
     * @date 2022/10/21 15:01
     * @since 1.0.0
     **/
    private static boolean isThisTime(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String dateFormat = sdf.format(date);
        String nowFormat = sdf.format(new Date());
        if (dateFormat.equals(nowFormat)) {
            return true;
        }
        return false;
    }


    /**
     * 判断是否是当天
     *
     * @param date 日期
     * @return boolean
     * @author compass
     * @date 2022/10/21 15:01
     * @since 1.0.0
     **/
    public static boolean isThisDay(Date date) {
        return isThisTime(date, "YYYY-MM-dd");
    }


    /**
     * 判断是否是本月
     *
     * @param date 日期
     * @return boolean
     * @author compass
     * @date 2022/10/21 15:01
     * @since 1.0.0
     **/
    public static boolean isThisMonth(Date date) {
        return isThisTime(date, "YYYY-MM-dd");
    }

    /**
     * 获取某月开始时间
     *
     * @param date 日期
     * @return java.time.LocalDateTime
     * @author compass
     * @date 2022/10/21 16:57
     * @since 1.0.0
     **/
    public static LocalDateTime getMonthBeginTime(Date date) {
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        YearMonth yearMonth = YearMonth.of(localDateTime.getYear(), localDateTime.getMonth());
        LocalDate localDate = yearMonth.atDay(1);
        return localDate.atStartOfDay();
    }


    /**
     * 获取某月开始时间
     *
     * @param date 日期字符串
     * @return java.time.LocalDateTime
     * @author compass
     * @date 2022/10/21 16:57
     * @since 1.0.0
     **/
    public static LocalDateTime getMonthBeginTime(String date) {
        return getMonthBeginTime(parse(date));
    }


    /**
     * 获取某月结束时间
     *
     * @param date 日期
     * @return java.time.LocalDateTime
     * @author compass
     * @date 2022/10/21 16:57
     * @since 1.0.0
     **/
    public static LocalDateTime getMonthEndTime(Date date) {
        LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        YearMonth yearMonth = YearMonth.of(localDateTime.getYear(), localDateTime.getMonth());
        LocalDate endOfMonth = yearMonth.atEndOfMonth();
        return endOfMonth.atTime(23, 59, 59, 999);
    }

    /**
     * 获取某月结束时间
     *
     * @param date 日期字符串
     * @return java.time.LocalDateTime
     * @author compass
     * @date 2022/10/21 16:57
     * @since 1.0.0
     **/
    public static LocalDateTime getMonthEndTime(String date) {
        return getMonthEndTime(parse(date));
    }

    /**
     * 获取指定时间范围内的所有日期[date]
     * @param dBegin 开始日期
     * @param dEnd 结束日期
     * @return java.util.List<java.util.Date>
     * @author compass
     * @date 2022/10/21 17:11
     * @since 1.0.0
     **/
    public static List<Date> findBetweenAll(Date dBegin, Date dEnd) {
        List<Date> dateList = new ArrayList<>();
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的开始时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的结束时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            dateList.add(calBegin.getTime());
        }
        return dateList;
    }

    /**
     * 获取指定时间范围内的所有日期[字符串]
     * @param dBegin 开始日期
     * @param dEnd 结束日期
     * @param format 日期格式字符串
     * @return java.util.List<java.util.Date>
     * @author compass
     * @date 2022/10/21 17:11
     * @since 1.0.0
     **/
    public static List<String> findBetweenAll(String dBegin, String dEnd,String format) {
        Date tempEndDate = parse(dEnd);
        List<String> dateList = new ArrayList<>();
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的开始时间
        calBegin.setTime(parse(dBegin));
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的结束时间
        calEnd.setTime(tempEndDate);
        // 测试此日期是否在指定日期之后
        while (tempEndDate.after(calBegin.getTime())) {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            String date = format( calBegin.getTime(),format);
            dateList.add(date);
        }
        return dateList;
    }



}

以上就是Java日期工具类的封装详解的详细内容,更多关于Java日期工具类的资料请关注编程学习网其它相关文章!

本文标题为:Java日期工具类的封装详解

基础教程推荐