日期处理工具类

package com.czqc.czc.buz.api.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;


public class DateUtils {
    protected static final Logger logger = LoggerFactory.getLogger(DateUtils.class);

    //一天的秒数
    private static final long DAY_SECOND = 24 * 60 * 60;

    //一天的毫秒数
    private static final long DAY_MILLISECOND = 24 * 60 * 60 * 1000;

    /**
     * 获取身份证号码的生日
     *
     * @return
     */
    public static String getIdCardBirthday(String idCardCode) throws Exception {
        String birthday = idCardCode.substring(6, 14);
        Date date = new SimpleDateFormat("yyyyMMdd").parse(birthday);
        return DateFormatUtils.format(date, "yyyy-MM-dd");
    }

    /**
     * 根据格式获当天日期
     */
    public static String formatNow(String pattern) {
        pattern = StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern;
        Date now = new Date();
        return DateFormatUtils.format(now, pattern);
    }

    /**
     * 将指定格式的字符串转为LocalDate
     *
     * @param str    时间字符串
     * @param format 现有格式
     * @return
     */
    public static LocalDate strToLocalDate(String str, String format) {
        try {
            if ("长期".equals(str)) return LocalDate.now().plusYears(100);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            Date date = simpleDateFormat.parse(str);
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            return instant.atZone(zoneId).toLocalDate();
        } catch (ParseException e) {
            e.printStackTrace();
            return LocalDate.now();
        }
    }

    /**
     * 格式化LocalDateTime
     */
    public static String formatLocalDateTime(LocalDateTime dateTime, String format) {
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(StringUtils.isNotEmpty(format) ? format : "yyyy-MM-dd HH:mm:ss");
        return dateTime.format(pattern);
    }


    /**
     * 时间戳转ZonedDateTime
     *
     * @param times 时间戳(毫秒)
     * @return
     */
    public static ZonedDateTime toZonedDateTimeMilli(Long times) {
        Instant instant = Instant.ofEpochMilli(times);
        return ZonedDateTime.ofInstant(instant, ZonedDateTime.now().getZone());
    }

    /**
     * 时间戳转ZonedDateTime
     *
     * @param times 时间戳(秒)
     * @return
     */
    public static ZonedDateTime toZonedDateTimeSecond(Long times) {
        Instant instant = Instant.ofEpochSecond(times);
        return ZonedDateTime.ofInstant(instant, ZonedDateTime.now().getZone());
    }

    /**
     * 转换时区
     *
     * @param targetTime 目标时间
     * @param resultTime 响应时间
     * @return
     */
    public static ZonedDateTime convertTimeZoned(ZonedDateTime targetTime, LocalDateTime resultTime) {
        ZoneId zoneId = ZoneId.of(targetTime.getZone().toString());
        ZonedDateTime time = ZonedDateTime.of(resultTime, zoneId);
        return time;
    }


    /**
     * 格式化ZonedDateTime
     *
     * @param time   时间
     * @param format 格式
     * @return
     */
    public static String toFormat(ZonedDateTime time, String format) {
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
        return time.format(pattern);
    }

    public static String toFormat(LocalDateTime time, String format) {
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
        return time.format(pattern);
    }

    public static String toFormat(LocalDate time, String format) {
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
        return time.format(pattern);
    }

    public static String toFormat(ZonedDateTime time) {
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return time.format(pattern);
    }

    public static String toFormat(LocalDateTime time) {
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return time.format(pattern);
    }


    /**
     * 将字符串转换成时间戳
     *
     * @param time 时间
     * @return
     */
    public static Long toEpochMillisecond(String time) {
        long timeMillis = 0l;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            timeMillis = dateFormat.parse(time).getTime();
        } catch (ParseException p) {
            logger.debug("转换时间为时间戳异常,传入的时间格式必须是:yyyy-MM-dd HH:mm:ss", p);
        }
        return timeMillis;
    }

    /**
     * 返回当前时间距离结束时间的秒数
     *
     * @param endZonedDateTime 结束时间
     *                         风险:如果传入时间为空则返回0L
     * @return 毫秒数
     */
    public static Long nowTmToEndTmTimeMillis(ZonedDateTime endZonedDateTime) {
        if (null == endZonedDateTime) {
            return 0L;
        }
        Long nowTime = toEpochMillisecond(ZonedDateTime.now());
        Long endTime = toEpochMillisecond(endZonedDateTime);
        return endTime - nowTime;
    }

    /**
     * 判断当前时间是否在开始时间和结束时间内
     *
     * @param startTm 开始时间
     * @param endTm   结束时间
     * @return true:在区间内
     */
    public static boolean isBetweenStartTmAndEndTm(ZonedDateTime startTm, ZonedDateTime endTm) {
        ZonedDateTime nowDate = ZonedDateTime.now();
        if (null == startTm && null == endTm) {
            return true;
        } else if (null == startTm && null != endTm && nowDate.isBefore(endTm)) {
            return true;
        } else if (null != startTm && null == endTm && nowDate.isAfter(startTm)) {
            return true;
        } else if (null != startTm && null != endTm && nowDate.isBefore(endTm) && nowDate.isAfter(startTm)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 将字符串转换成ZonedDateTime
     *
     * @param time
     */
    public static ZonedDateTime strToZonedDateTime(String time) {
        return toZonedDateTimeMilli(toEpochMillisecond(time));
    }

    /**
     * 将时间戳转字符串的时间
     *
     * @param timeMillis
     */
    public static String timeMillisToString(Long timeMillis) {
        return toFormat(toZonedDateTimeMilli(timeMillis));
    }

    /**
     * ZonedDateTime 转时间戳(毫秒)
     *
     * @param zonedDateTime
     * @return
     */
    @Deprecated
    public static Long zonedDateTimeToTimeMillis(ZonedDateTime zonedDateTime) {
        if (null == zonedDateTime) return 0L;
        return toEpochMillisecond(toFormat(zonedDateTime));
    }

    /**
     * ZonedDateTime 转时间戳(秒)
     *
     * @param zonedDateTime
     * @return
     */
    public static Long toEpochSecond(ZonedDateTime zonedDateTime) {
        return zonedDateTime.toEpochSecond();
    }

    /**
     * ZonedDateTime 转时间戳(毫秒)
     *
     * @param zonedDateTime
     * @return
     */
    public static Long toEpochMillisecond(ZonedDateTime zonedDateTime) {
        return zonedDateTime.toInstant().toEpochMilli();
    }


    /**
     * 获取当天的结束时间
     *
     * @return
     */
    public static ZonedDateTime getDayTimeMAX() {
        return ZonedDateTime.of(LocalDateTime.of(LocalDate.now(), LocalTime.MAX), ZonedDateTime.now().getZone());
    }

    /**
     * 获取当天的结束时间
     *
     * @return
     */
    public static ZonedDateTime getDayTimeMAXV2() {
        return ZonedDateTime.of(LocalDate.now().atTime(LocalTime.MAX), ZonedDateTime.now().getZone());
    }

    /**
     * 获取日期的结束时间
     *
     * @return
     */
    public static ZonedDateTime getDayTimeMAX(LocalDate localDate) {
        return ZonedDateTime.of(LocalDateTime.of(localDate, LocalTime.MAX), ZonedDateTime.now().getZone());
    }


    /**
     * 获取当天的开始时间
     *
     * @return
     */
    public static ZonedDateTime getDayTimeMIN() {
        return ZonedDateTime.of(LocalDateTime.of(LocalDate.now(), LocalTime.MIN), ZonedDateTime.now().getZone());
    }

    /**
     * 获取当天的开始时间
     *
     * @return
     */
    public static ZonedDateTime getDayTimeMINV2() {
        return LocalDate.now().atStartOfDay(ZonedDateTime.now().getZone());
    }

    /**
     * 获取日期的开始时间
     *
     * @return
     */
    public static ZonedDateTime getDayTimeMIN(LocalDate localDate) {
        return ZonedDateTime.of(LocalDateTime.of(localDate, LocalTime.MIN), ZonedDateTime.now().getZone());
    }

    /**
     * 获取当月第一天的开始时间
     *
     * @return
     */
    public static ZonedDateTime getCurrMonthStartTimeMin() {
        return getDayTimeMINV2().withDayOfMonth(1);
    }

    /**
     * 获取当月第一天的开始时间 字符串格式
     *
     * @return
     */
    public static String getCurrMonthStartTimeMinStr() {
        return toFormat(getCurrMonthStartTimeMin());
    }


    /**
     * 获取月第一天的开始时间
     *
     * @return
     */
    public static ZonedDateTime getMonthStartTimeMin(LocalDate localDate) {
        return getDayTimeMIN(localDate).withDayOfMonth(1);
    }

    /**
     * 获取月第一天的开始时间 字符串格式
     *
     * @return
     */
    public static String getMonthStartTimeMinStr(LocalDate localDate) {
        return toFormat(getMonthStartTimeMin(localDate));
    }

    /**
     * 获取当月第一天的结束时间
     *
     * @return
     */
    public static ZonedDateTime getCurrMonthStartTimeMax() {
        return getDayTimeMAXV2().withDayOfMonth(1);
    }

    /**
     * 获取当月第一天的结束时间 字符串格式
     *
     * @return
     */
    public static String getCurrMonthStartTimeMaxStr() {
        return toFormat(getCurrMonthStartTimeMax());
    }

    /**
     * 获取月第一天的结束时间
     *
     * @return
     */
    public static ZonedDateTime getMonthStartTimeMax(LocalDate localDate) {
        return getDayTimeMAX(localDate).withDayOfMonth(1);
    }

    /**
     * 获取月第一天的结束时间 字符串格式
     *
     * @return
     */
    public static String getMonthStartTimeMaxStr(LocalDate localDate) {
        return toFormat(getMonthStartTimeMax(localDate));
    }

    /**
     * 获取当月最后一天的开始时间
     *
     * @return
     */
    public static ZonedDateTime getCurrMonthEndTimeMin() {
        return getMonthStartTimeMin(LocalDate.now().plusMonths(1)).minusDays(1);
    }

    /**
     * 获取当月最后一天的开始时间 字符串格式
     *
     * @return
     */
    public static String getCurrMonthEndTimeMinStr() {
        return toFormat(getCurrMonthEndTimeMin());
    }

    /**
     * 获取月最后一天的开始时间
     *
     * @return
     */
    public static ZonedDateTime getMonthEndTimeMin(LocalDate localDate) {
        return getMonthStartTimeMin(localDate.plusMonths(1)).minusDays(1);
    }


    /**
     * 获取月最后一天的开始时间 字符串格式
     *
     * @return
     */
    public static String getCurrMonthEndTimeMinStr(LocalDate localDate) {
        return toFormat(getMonthEndTimeMin(localDate));
    }

    /**
     * 获取当月最后一天的结束时间
     *
     * @return
     */
    public static ZonedDateTime getCurrMonthEndTimeMax() {
        return getMonthStartTimeMax(LocalDate.now().plusMonths(1)).minusDays(1);
    }

    /**
     * 获取当月最后一天的结束时间 字符串格式
     *
     * @return
     */
    public static String getCurrMonthEndTimeMaxStr() {
        return toFormat(getCurrMonthEndTimeMax());
    }

    /**
     * 获取月最后一天的结束时间
     *
     * @param localDate
     * @return
     */
    public static ZonedDateTime getMonthEndTimeMax(LocalDate localDate) {
        return getMonthStartTimeMax(localDate.plusMonths(1)).minusDays(1);
    }

    /**
     * 获取月最后一天的结束时间 字符串格式
     *
     * @param localDate
     * @return
     */
    public static String getMonthEndTimeMaxStr(LocalDate localDate) {
        return toFormat(getMonthEndTimeMax(localDate));
    }

    /**
     * 计算两个日期间隔的天数
     *
     * @param start
     * @param end
     * @return
     */
    public static long betweenDaysNumber(ZonedDateTime start, ZonedDateTime end) {
        long betweenSecond = Math.abs(toEpochSecond(start) - toEpochSecond(end));
        return betweenSecond / DAY_SECOND;
    }

    /**
     * 计算日期总天数
     *
     * @param start
     * @param end
     * @return
     */
    public static long betweenTotalDaysNumber(ZonedDateTime start, ZonedDateTime end) {
        return betweenDaysNumber(start, end) + 1;
    }

    /**
     * 查询当月天数
     *
     * @return
     */
    public static long getCurrMonthDayNumber() {
        ZonedDateTime currMonthStartTimeMin = getCurrMonthStartTimeMin();
        ZonedDateTime currMonthEndTimeMin = getCurrMonthEndTimeMin();
        return betweenTotalDaysNumber(currMonthStartTimeMin, currMonthEndTimeMin);
    }

    /**
     * 计算月的天数
     *
     * @param month
     * @return
     */
    public static long getMonthDayNumber(int month) {
        LocalDate localDate = LocalDate.now().withMonth(month);
        ZonedDateTime currMonthStartTimeMin = getMonthStartTimeMin(localDate);
        ZonedDateTime currMonthEndTimeMin = getMonthEndTimeMin(localDate);
        return betweenTotalDaysNumber(currMonthStartTimeMin, currMonthEndTimeMin);
    }

    /**
     * 获取当月的第一天日期
     */
    public static LocalDate getCurrMonthStartDate() {
        return getCurrMonthStartTimeMin().toLocalDate();
    }

    /**
     * 获取当月的最后一天日期
     */
    public static LocalDate getCurrMonthEndDate() {
        return getCurrMonthEndTimeMax().toLocalDate();
    }

    /**
     * 获取当前时间到当天结束时间的秒数
     *
     * @return 秒
     */
    public static Long nowTmToCurrDayEndTmTimeSecond() {
        try {
            return nowTmToEndTmTimeMillis(getDayTimeMAX()) / 1000;
        } catch (Exception e) {
            e.printStackTrace();
            return 0l;
        }
    }

    /**
     * 计算 day 天后的时间
     * @param date
     * @param day
     * @return
     */
    public static Date addDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        return calendar.getTime();
    }

    /**
     * Date 转 LocalDateTime
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    /**
     * LocalDateTime 转 Date
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return Date.from(instant);
    }

    /**
     * 计算 year 后的时间
     * @param date
     * @param month
     * @return
     */
    public static Date addMonth(Date date, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTime();
    }


    /**
     * 计算 year 后的时间
     * @param date
     * @param year
     * @return
     */
    public static Date addYear(Date date, int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
        return calendar.getTime();
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.addMonth(new Date(),5));
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值