IT俱乐部 Java Java日期工具类的封装详解

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> 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 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 
     * yyyy-MM-dd HH:mm:ss.SSS 
* yyyy-MM-dd HH:mm:ss
* yyyy-MM-dd
* yyyy.MM.dd
* yyyy/MM/dd
* HH:mm:ss.SSS
* HH:mm:ss
* yyyyMMdd
* yyyyMMddHHmmssSSS
* yyyyMMddHHmmss
* yyyyMM
* * @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 1) { throw new RuntimeException("日期格式字符串,只支持一个"); } int days = 0; try { SimpleDateFormat myFormatter = new SimpleDateFormat(format.length 1) { throw new RuntimeException("日期格式字符串,只支持一个"); } long time = ManagementFactory.getRuntimeMXBean().getStartTime(); return format(new Date(time), format.length = 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 * @author compass * @date 2022/10/21 17:11 * @since 1.0.0 **/ public static List findBetweenAll(Date dBegin, Date dEnd) { List 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 * @author compass * @date 2022/10/21 17:11 * @since 1.0.0 **/ public static List findBetweenAll(String dBegin, String dEnd,String format) { Date tempEndDate = parse(dEnd); List 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日期工具类的资料请关注IT俱乐部其它相关文章!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/7039.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部