分享日期处理工具类--DateUtils

package com.hl.analyze.utils;

import com.google.common.collect.Lists;
import com.hl.analyze.utils.enums.DateFmtEnum;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author Starry
 * @date 9:46 2018/4/13 Modified By:
 */

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DateUtils {
    private static final Logger log = LoggerFactory.getLogger(DateUtils.class);

    /**
     * 日期格式化
     */
    private static final String GS = "yyyy-MM-dd HH:mm:ss";
    private static final DateTimeFormatter DF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 日期转换字符串
     */
    public static String parseDate(Date date, String gs) {
        SimpleDateFormat sdf = new SimpleDateFormat(gs);
        return sdf.format(date);

    }

    /**
     * 准换字符串
     *
     * @param strDate 要转换的日期
     * @param pat2    转换后的日期格式
     */
    public static String str2Str(String strDate, String pat2) {
        // 实例化模板对象
        SimpleDateFormat sdf1 = new SimpleDateFormat(GS);
        // 实例化模板对象
        SimpleDateFormat sdf2 = new SimpleDateFormat(pat2);
        Date d = null;
        try {
            // 将给定的字符串中的日期提取出来
            d = sdf1.parse(strDate);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        // 将日期变为新的格式
        return (sdf2.format(d));
    }

    public static String parseDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(GS);
        return sdf.format(date);
    }

    /**
     * 字符串转为日期
     */
    public static Date stringToDate(String time, String gs) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(gs);
        Date d = null;
        try {
            d = sDateFormat.parse(time);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return d;

    }

    public static String getSpecifiedDayBefore(String specifiedDay) {

        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }

        c.setTime(date);
        int day = c.get(Calendar.DATE);

        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());

        return dayBefore;

    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getDate() {
        Date date = new Date();
        String d = parseDate(date, "yyyy-MM-dd HH:mm:ss");
        return d;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getDateDay() {
        Date date = new Date();
        String d = parseDate(date, "yyyy-MM-dd");
        return d;
    }

    public static Integer getDifference(Date beginTime, Date endTime) {
        return (int) ((endTime.getTime() - beginTime.getTime()) / (1000 * 3600 * 24));
    }

    /**
     * @Description yyyy-MM-dd HH:mm:ss
     */
    public static Integer getDifference(String beginTime, String endTime) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(GS);
        Date beginDate = format.parse(beginTime);
        Date endDate = format.parse(endTime);

        return (int) ((endDate.getTime() - beginDate.getTime()) / (1000 * 3600 * 24));
    }

    /**
     * @Description yyyy-MM-dd HH:mm:ss
     */
    public static List<String> getDifferenceList(String beginTime, String endTime) throws ParseException {
        LinkedList<String> result = Lists.newLinkedList();
        LocalDateTime begin = LocalDateTime.parse(beginTime, DF);
        LocalDateTime end = LocalDateTime.parse(endTime, DF);
        int i = end.compareTo(begin);
        if (i == 1 && !end.toLocalDate().toString().equals(begin.toLocalDate().toString())) {
            result.add(begin.toLocalDate().toString());
            result.add(end.toLocalDate().toString());
            return result;
        }
        if (i == 1 && end.toLocalDate().toString().equals(begin.toLocalDate().toString())) {
            result.add(begin.toLocalDate().toString());
            return result;
        } else if (i > 1) {
            for (int j = 0; j <= i; j++) {
                result.add(begin.toLocalDate().plusDays(j).toString());
            }

        }
        return result;
    }

    /**
     * 获取输入时间与当前时间的差
     *
     * @param time  比较时间
     * @param level 深入层,x年x月x天x时x秒之前,level用来确定精确层数,比如level=2 则x年x月 若年为0 则x月x天
     * @return x年x月x天x时x秒之前,层数受level约束
     */
    public static String getDateDiffForNow(LocalDateTime time, int level) {
        return getDateDiffStr(time, LocalDateTime.now(), level);
    }

    /**
     * 获取输入时间之间时间差
     *
     * @param before 之前时间
     * @param after  之后时间
     * @param level  深入层,x年x月x天x时x秒之前,level用来确定精确层数,比如level=2 则x年x月 若年为0 则x月x天
     * @return x年x月x天x时x秒,层数受level约束
     */
    public static String getDateDiffStr(LocalDateTime before, LocalDateTime after, int level) {
        int currLevel = 0;
        long lastData = 0;
        List<ChronoUnit> chL = Arrays.asList(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.HOURS,
                ChronoUnit.MINUTES, ChronoUnit.SECONDS);
        // 记录中文的时间描述
        String[] desCn = {"年", "月", "天", "小时", "分", "秒"};
        // 记录相邻的两个时间刻度之间的转换值,为方便计算,第一位为空缺0
        int[] diff = {0, 12, 30, 24, 60, 60};

        StringBuilder timeSb = new StringBuilder();

        for (int i = 0; i < chL.size(); i++) {
            long cal = chL.get(i).between(before, after);
            if (cal != 0) {
                timeSb.append(cal - lastData * diff[i]).append(desCn[i]);
                currLevel++;
                lastData = cal;

                if (currLevel == level) {
                    break;
                }
            }
        }

        return timeSb.toString();
    }

    /**
     * 返回当前时间字符串,格式:yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getNowStr() {
        return getNowStr(com.hl.analyze.utils.enums.DateFmtEnum.FMT_SECODE_HYPHEN);
    }

    /**
     * 根据格式化格式返回当前时间
     *
     * @param fmt 格式化
     * @return
     */
    public static String getNowStr(com.hl.analyze.utils.enums.DateFmtEnum fmt) {
        return getNowStr(fmt.getValue());
    }

    /**
     * 根据格式化格式返回当前时间
     *
     * @param fmt 格式化
     * @return
     */
    public static String getNowStr(String fmt) {
        return localDateTimeFmt(LocalDateTime.now(), fmt);
    }

    /**
     * 将时间格式化为字符串,默认格式化为yyyy-MM-dd HH:mm:ss
     *
     * @param time 时间
     * @return
     */
    public static String localDatetimeFmt(LocalDateTime time) {
        return localDateTimeFmt(time, com.hl.analyze.utils.enums.DateFmtEnum.FMT_SECODE_HYPHEN);
    }

    /**
     * 将时间格式化为字符串
     *
     * @param time 时间
     * @param fmt  格式化
     * @return
     */
    public static String localDateTimeFmt(LocalDateTime time, DateFmtEnum fmt) {
        return localDateTimeFmt(time, fmt.getValue());
    }

    /**
     * 将时间格式化为字符串
     *
     * @param time 时间
     * @param fmt  格式化
     * @return
     */
    public static String localDateTimeFmt(LocalDateTime time, String fmt) {
        return time.format(DateTimeFormatter.ofPattern(fmt));
    }

    /**
     * 计算日期时间差(小时)
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long getDateHour(Date startDate, Date endDate) {
        long nd = 1000 * 60 * 60L;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();
        // 计算差多少天
//        long day = diff / nd /24;
        // 计算差多少小时
        long hour = diff / nd;
        return hour;
    }

    /**
     * 计算日期时间差(分钟)
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    public static long getDateMinute(Date startDate, Date endDate) {
        long nd = 1000 * 60L;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();
        // 计算差多少分钟
        long minute = diff / nd;
        return minute;
    }

    /**
     * 计算当前时间到次日0点秒数
     *
     * @return
     */
    public static long getTomorrowZeroSeconds() {
        // 当前时间毫秒数
        long current = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long tomorrowzero = calendar.getTimeInMillis();
        long tomorrowzeroSeconds = (tomorrowzero - current) / 1000;
        return tomorrowzeroSeconds;
    }

    /**
     * 获取之前日期
     *
     * @param amount 相差的天数
     */
    public static String getThePreviousDay(Integer amount) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, amount);
        SimpleDateFormat sdf = new SimpleDateFormat(GS);
        return sdf.format(calendar.getTime());
    }

    public static List<String> getThePreviousSixDaysDate() {
        ArrayList<String> dateList = Lists.newArrayList();
        dateList.add(DateUtils.getThePreviousDay(-1));
        dateList.add(DateUtils.getThePreviousDay(-2));
        dateList.add(DateUtils.getThePreviousDay(-3));
        dateList.add(DateUtils.getThePreviousDay(-4));
        dateList.add(DateUtils.getThePreviousDay(-5));
        dateList.add(DateUtils.getThePreviousDay(-6));
        return dateList;
    }

    /**
     * @param currentDateTime 当前时间
     * @return boolean
     * @Description 大于当前时间为true
     */
    public static boolean isItGreaterThanTheCurrentDate(String currentDateTime) {
        SimpleDateFormat sdf = new SimpleDateFormat(GS);

        Date today = new Date();

        try {
            //将字符串转换为 date 类型  Debug:Sun Nov 11 00:00:00 CST 2018
            Date dateD = sdf.parse(currentDateTime);
            return dateD.getTime() >= today.getTime();
        } catch (ParseException e1) {
            e1.printStackTrace();
            return false;
        }
    }
    public static List<DateSplit> splitByMinute(Date startTime, Date endTime, int intervalMinutes) {
        if (endTime.getTime() <= startTime.getTime()) {
            return null;
        }
        List<DateSplit> dateSplits = new ArrayList<>(256);

        DateSplit param = new DateSplit();
        param.setStartDateTime(startTime);
        param.setEndDateTime(endTime);
        param.setEndDateTime(addMinute(startTime, intervalMinutes));
        while (true) {
            param.setStartDateTime(startTime);
            Date tempEndTime = addMinute(startTime, intervalMinutes);
            if (tempEndTime.getTime() >= endTime.getTime()) {
                tempEndTime = endTime;
            }
            param.setEndDateTime(tempEndTime);

            dateSplits.add(new DateSplit(param.getStartDateTime(), param.getEndDateTime()));

            startTime = addMinute(startTime, intervalMinutes);
            if (startTime.getTime() >= endTime.getTime()) {
                break;
            }
            if (param.getEndDateTime().getTime() >= endTime.getTime()) {
                break;
            }
        }
        return dateSplits;
    }
    private static String formatDateTime(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class DateSplit {
        private Date startDateTime;
        private Date endDateTime;

        public String getStartDateTimeStr() {
            return formatDateTime(startDateTime);
        }

        public String getEndDateTimeStr() {
            return formatDateTime(endDateTime);
        }
    }
    private static Date addDays(Date date, int days) {
        return add(date, Calendar.DAY_OF_MONTH, days);
    }

    private static Date addHours(Date date, int hours) {
        return add(date, Calendar.HOUR_OF_DAY, hours);
    }

    private static Date addMinute(Date date, int minute) {
        return add(date, Calendar.MINUTE, minute);
    }
    private static Date addSeconds(Date date, int second) {
        return add(date, Calendar.SECOND, second);
    }

    private static Date add(final Date date, final int calendarField, final int amount) {
        final Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }
}

 

posted @ 2022-03-24 15:33  jiuchengi  阅读(95)  评论(0编辑  收藏  举报