日期處理工具類

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));
    }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章