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日期工具類的資料請關註WalkonNet其它相關文章!

推薦閱讀: