日期操作工具类

日期操作工具类DateUtils

日期操作工具类DateUtils

public class DateUtils extends org.apache.commons.lang3.time.DateUtils {


    /**
     * 获取指定日期格式的当前日期字符串
     *
     * @param format 日期格式
     * @return String
     */
    public static String getNowDate(String format) {
        return parseDateToStr(format, new Date());
    }

    /**
     * 得到当前系统日期 日期格式为"yyyy-MM-dd"
     *
     * @return String,
     */
    public static String getCurrentDate() {
        return parseDateToStr(DateTypeEnum.YYYY_MM_DD.getValue(), new Date());
    }

    /**
     * 得到当前系统时间 时间格式为"HH:mm:ss"
     *
     * @return String
     */
    public static String getCurrentTime() {
        return parseDateToStr(DateTypeEnum.HH_MM_SS.getValue(), new Date());
    }

    /**
     * 日期格式转换 "yyyy-MM-dd"字符串 转 Date型
     *
     * @param strDate 日期字符串
     * @return Date
     */
    public static final Date parseStrToDate(final String strDate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateTypeEnum.YYYY_MM_DD.getValue());
        Date date = null;
        try {
            date = simpleDateFormat.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 日期格式转换 Date型转指定格式的日期字符串
     *
     * @param format 日期格式
     * @param date   日期
     * @return String
     */
    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 日期格式转换 "YYYY年MM月DD日"的格式,输入格式为"YYYY/MM/DD","YYYY-MM-DD",月日去0型
     *
     * @param cDate 日期字符串
     * @return String "YYYY年MM月DD日"的格式日期,月日前去0
     */
    public static String formatDateEx(String cDate) {
        if (cDate == null || "".equals(cDate)) {
            return "";
        }

        //年月日
        String year = "";
        String month = "";
        String day = "";

        if (cDate.indexOf("-") != -1) {
            year = cDate.substring(0, cDate.indexOf("-"));
            month = cDate.substring(cDate.indexOf("-") + 1,
                    cDate.lastIndexOf("-"));
            day = cDate.substring(cDate.lastIndexOf("-") + 1);
        } else if (cDate.indexOf("/") != -1) {
            year = cDate.substring(0, cDate.indexOf("/"));
            month = cDate.substring(cDate.indexOf("/") + 1,
                    cDate.lastIndexOf("/"));
            day = cDate.substring(cDate.lastIndexOf("/") + 1);
        }

        //月前面去零
        if (month.startsWith("0")) {
            month = month.substring(1);
        }

        //日前面去零
        if (day.startsWith("0")) {
            day = day.substring(1);
        }

        cDate = year + "年" + month + "月" + day + "日";
        return cDate;
    }

    /**
     * 判断是否为闰年
     *
     * @param nYear 年份
     * @return true-闰年;false-平年
     */
    public static boolean isLeapYear(int nYear) {
        return (nYear % 400 == 0) | (nYear % 100 != 0) & (nYear % 4 == 0);
    }

    /**
     * 正则表达式判断字符串日期是否有效:包括年月日,闰年、平年和每月31天、30天和闰月的28天或者29天
     *
     * @param strDate Year-Month-Day
     * @return true-有效;false-无效
     */
    public static boolean isValidDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 日期计算 计算日期的函数
     *
     * <pre>
     *     DateUtils.calDate("2021-01-01", 3, "D")  -> 2021-01-04
     *     DateUtils.calDate("2021-01-01", 3, "M")  -> 2021-04-01
     *     DateUtils.calDate("2021-01-01", 3, "Y")  -> 2024-01-01
     * </pre>
     * @param baseDate    起始日期
     * @param interval    时间间隔
     * @param unit        时间间隔单位
     * @return Date
     */
    public static Date calDate(Date baseDate, int interval, String unit) {
        Date returnDate = null;

        GregorianCalendar tBaseCalendar = new GregorianCalendar();
        tBaseCalendar.setTime(baseDate);

        if (unit.equalsIgnoreCase(DateTypeEnum.Y.getValue())) {
            tBaseCalendar.add(Calendar.YEAR, interval);
        }
        if (unit.equalsIgnoreCase(DateTypeEnum.M.getValue())) {
            tBaseCalendar.add(Calendar.MONTH, interval);
        }
        if (unit.equalsIgnoreCase(DateTypeEnum.D.getValue())) {
            tBaseCalendar.add(Calendar.DATE, interval);
        }

        returnDate = tBaseCalendar.getTime();

        //闰年闰月和月底天数,和Oracle保持一致
        GregorianCalendar tLeapCalendar = new GregorianCalendar();
        tLeapCalendar.setTime(returnDate);
        int arrComnYearEndDate[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int arrLeapYearEndDate[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int nOldYear = 1900 + baseDate.getYear();
        int nOldMonth = baseDate.getMonth();
        int nOldDate = baseDate.getDate();
        int nNewYear = tLeapCalendar.get(Calendar.YEAR);
        int nNewMonth = tLeapCalendar.get(Calendar.MONTH);

        if ((isLeapYear(nOldYear) && nOldDate == arrLeapYearEndDate[nOldMonth]) ||
                (!isLeapYear(nOldYear) && nOldDate == arrComnYearEndDate[nOldMonth])) {
            if (unit != null && (unit.equalsIgnoreCase(DateTypeEnum.Y.getValue()) || unit.equalsIgnoreCase(DateTypeEnum.M.getValue()))) {
                if (isLeapYear(nNewYear)) {
                    returnDate.setDate(arrLeapYearEndDate[nNewMonth]);
                } else {
                    returnDate.setDate(arrComnYearEndDate[nNewMonth]);
                }
            }
        }
        return returnDate;
    }

    /**
     * 日期计算 通过起始日期和终止日期计算以时间间隔单位为计量标准的时间间隔,舍弃法
     *
     * <pre>
     *     DateUtils.calInterval("2021-02-01","2021-02-04","D") -> 3
     * </pre>
     *
     * @param cstartDate 起始日期,格式:"YYYY-MM-DD"
     * @param cendDate   终止日期,格式:"YYYY-MM-DD"
     * @param unit       时间间隔单位,可用值"Y"--年 "M"--月 "D"--日
     * @return int 时间间隔
     */
    public static int calInterval(String cstartDate, String cendDate, String unit) {

        //先判断是否是有效格式日期
        if (!isValidDate(cstartDate) || !isValidDate(cendDate)) {
            return 0;
        }

        int interval = 0;

        GregorianCalendar sCalendar = new GregorianCalendar();
        sCalendar.setTime(parseStrToDate(cstartDate));
        int sYears = sCalendar.get(Calendar.YEAR);
        int sMonths = sCalendar.get(Calendar.MONTH);
        int sDays = sCalendar.get(Calendar.DAY_OF_MONTH);

        GregorianCalendar eCalendar = new GregorianCalendar();
        eCalendar.setTime(parseStrToDate(cendDate));
        int eYears = eCalendar.get(Calendar.YEAR);
        int eMonths = eCalendar.get(Calendar.MONTH);
        int eDays = eCalendar.get(Calendar.DAY_OF_MONTH);

        if (DateTypeEnum.Y.getValue().equalsIgnoreCase(unit.trim())) {
            interval = eYears - sYears;

            if (eMonths < sMonths) {
                interval--;
            } else {
                if (eMonths == sMonths && eDays < sDays) {
                    interval--;
                    if (eMonths == 1) { //如果同是2月,校验润年问题
                        if ((sYears % 4) == 0 && (eYears % 4) != 0) { //如果起始年是润年,终止年不是润年
                            if (eDays == 28) { //如果终止年不是润年,且2月的最后一天28日,那么补一
                                interval++;
                            }
                        }
                    }
                }
            }
        }
        if (DateTypeEnum.M.getValue().equalsIgnoreCase(unit.trim())) {
            interval = eYears - sYears;
            interval *= 12;
            interval += eMonths - sMonths;

            if (eDays < sDays) {
                interval--;
                //eDays如果是月末,则认为是满一个月
                int maxDate = eCalendar.getActualMaximum(Calendar.DATE);
                if (eDays == maxDate) {
                    interval++;
                }
            }
        }
        if (DateTypeEnum.D.getValue().equalsIgnoreCase(unit.trim())) {
            sCalendar.set(sYears, sMonths, sDays);
            eCalendar.set(eYears, eMonths, eDays);
            long lInterval = (eCalendar.getTime().getTime() -
                    sCalendar.getTime().getTime()) / 86400000;
            interval = (int) lInterval;
        }
        return interval;
    }


    /**
     * 指定日期加上天数后的日期
     *
     * @param startDate 开始计算日期
     * @param day       为增加的天数
     * @return
     */
    public static Date addDate(Date startDate, Double day) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
        long time = startDate.getTime(); // 得到指定日期的毫秒数
        Double num = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
        time += num; // 相加得到新的毫秒数
        Date newDate = new Date(time);
        try {
            return DateUtils.parseDate(dateFormat.format(newDate)); // 将毫秒数转换成日期,返回日期对象
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

日期类型枚举类

public enum DateTypeEnum {
    Y("Y", "年"),
    M("M", "月"),
    D("D", "日"),
    YYYY_MM_DD("yyyy-MM-dd", "年-月-日"),
    HH_MM_SS("HH:mm:ss", "时:分:秒"),
    YYYY_MM_DD_HH_MM_SS("yyyy-MM-dd HH:mm:ss", "年-月-日 时:分:秒"),
    DATEPATH("yyyy/MM/dd", "年/月/日"),
    DATETIME("yyyyMMdd", "年月日"),
    ;

    private String value;
    private String text;

    DateTypeEnum(String value, String text) {
        this.value = value;
        this.text = text;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
上一篇:Leetcode 435. Non-overlapping Intervals (贪心)


下一篇:期中测验题目及参考答案 类-对象-运算符重载