DateUtil-日期工具类

3,374 阅读8分钟
  1. 获取当前时间时间戳(long);

  2. 获取当前日期,包含时分秒(yyyy-MM-dd HH:mm:ss);

  3. 获取当前日期,不包含时分秒(yyyy-MM-dd);

  4. 得到两个时间差 格式yyyy-MM-dd HH:mm:ss;

  5. 转化long值的日期时间戳为yyyy-MM-dd HH:mm:ss.SSS格式的日期;

  6. 获取当前日期是一个星期的第几天;

  7. 获取当前小时 :2019-08-23 17;

  8. 获取当前时间一个小时前 2019-08-23 16;

  9. 获取当前日期前一天 2019-08-22;

  10. 获取最近七天 2019-08-20(有时候用于查最近七天数据起始时间);

  11. 获取最近一个月 2019-07-20 (有时候用于查最近一个月数据起始时间);

  12. 获取最近三个月 2019-05-20 (有时候用于查最近三个月数据起始时间);

  13. 获取最近一年 2018-08-20 (有时候用于查最近一年数据起始时间);

  14. 获取今年月份数据list(比如当前月为8月,返回list中包含8个数据1-8);

  15. 获取今年季度数据list(比如当前月为8月,为一年中第三个季度,返回list中包含3个数据1-3)

  16. 获取几天前的时间

  17. 获取几天后的时间

  18. 返回n天前开始的时间

  19. 返回两个日期中的最大值

  20. 获取date日期hours小时后的时间

  21. 获取date日期seconds小时后的时间

  22. 日期格式化string

  23. 获取当天剩余时间 秒

  24. String转换为Date

  25. 获取当前时间返回字符串

  26. 获取当前最早的时间 00:00:00

  27. 获取当前最后的时间 23:59:59

  28. 将给定时间增加day天

  29. 将给定时间减少day天

  30. 将当前时间减少hours小时

  31. 两个时间相差多少秒

  32. 将分秒清零

package com.qiaofang.propertycore.service.impl;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * @program: qf-jedi-estate
 * @description: 日期工具类
 * @author: 52Hz
 * @create: 2021-10-21 16:01
 **/
@Component
public class DateUtil {

    private static int month = Calendar.getInstance().get(Calendar.MONTH) + 1;

    private static final String SDFDATE = "yyyy-MM-dd";
    private static final String SDFDATE2 = "yyyy/MM/dd";
    private static final String SDFDATETIME = "yyyy-MM-dd HH:mm:ss";
    private static final String SDFDATETIME2 = "yyyy-MM-dd HH:mm";
    private static final String XGTIME = "yyyy/MM/dd HH:mm:ss";
    private static final String DMS = "yyyyMMddHHmmss";
    private static final String YYYY_MM_DD_HH = "yyyy-MM-dd HH";
    private static DateTimeFormatter dtfDatetime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static DateTimeFormatter SDFDATE_HOURS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00:00");

    /**
     * 获得当前日期 yyyy-MM-dd HH:mm:ss
     *
     * @return 2019-08-27 14:12:40
     */
    public static String getCurrentTime() {
        // 小写的hh取得12小时,大写的HH取的是24小时
        SimpleDateFormat df = new SimpleDateFormat(SDFDATETIME);
        Date date = new Date();
        return df.format(date);
    }

    /**
     * 获取系统当前时间戳
     *
     * @return 1566889186583
     */
    public static String getSystemTime() {
        String current = String.valueOf(System.currentTimeMillis());
        return current;
    }


    /**
     * 获取当前日期 yy-MM-dd
     *
     * @return 2019-08-27
     */
    public static String getDateByString() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(SDFDATE);
        return sdf.format(date);
    }

    /**
     * 得到两个时间差  格式yyyy-MM-dd HH:mm:ss
     *
     * @param start 2019-06-27 14:12:40
     * @param end   2019-08-27 14:12:40
     * @return 5270400000
     */
    public static long dateSubtraction(String start, String end) {
        SimpleDateFormat df = new SimpleDateFormat(SDFDATETIME);
        try {
            Date date1 = df.parse(start);
            Date date2 = df.parse(end);
            return date2.getTime() - date1.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 得到两个时间差
     *
     * @param start 开始时间
     * @param end   结束时间
     * @return
     */
    public static long dateTogether(Date start, Date end) {
        return end.getTime() - start.getTime();
    }

    /**
     * 转化long值的日期为yyyy-MM-dd  HH:mm:ss.SSS格式的日期
     *
     * @param millSec 日期long值  5270400000
     * @return 日期,以yyyy-MM-dd  HH:mm:ss.SSS格式输出 1970-03-03  08:00:00.000
     */
    public static String transferLongToDate(String millSec) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss.SSS");
        Date date = new Date(Long.parseLong(millSec));
        return sdf.format(date);
    }

    /**
     * 获得当前日期 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getOkDate(String date) {
        try {
            if (StringUtils.isEmpty(date)) {
                return null;
            }
            Date date1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH).parse(date);
            //格式化
            SimpleDateFormat sdf = new SimpleDateFormat(SDFDATETIME);
            return sdf.format(date1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取当前日期是一个星期的第几天
     *
     * @return 2
     */
    public static int getDayOfWeek() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        return cal.get(Calendar.DAY_OF_WEEK) - 1;
    }


    /**
     * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     *
     * @param nowTime     当前时间
     * @param dateSection 时间区间   2018-01-08,2019-09-09
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(Date nowTime, String dateSection) {
        try {
            String[] times = dateSection.split(",");
            String format = SDFDATE;
            Date startTime = new SimpleDateFormat(format).parse(times[0]);
            Date endTime = new SimpleDateFormat(format).parse(times[1]);
            if (nowTime.getTime() == startTime.getTime()
                    || nowTime.getTime() == endTime.getTime()) {
                return true;
            }
            Calendar date = Calendar.getInstance();
            date.setTime(nowTime);

            Calendar begin = Calendar.getInstance();
            begin.setTime(startTime);

            Calendar end = Calendar.getInstance();
            end.setTime(endTime);

            if (isSameDay(date, begin) || isSameDay(date, end)) {
                return true;
            }
            if (date.after(begin) && date.before(end)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 != null && cal2 != null) {
            return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }

    public static long getTimeByDate(String time) {
        SimpleDateFormat format = new SimpleDateFormat(SDFDATETIME);
        try {
            Date date = format.parse(time);
            //日期转时间戳(毫秒)
            return date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取当前小时 :2019-08-23 17
     *
     * @return 2019-08-27 17
     */
    public static String getCurrentHour() {
        GregorianCalendar calendar = new GregorianCalendar();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour < 10) {
            return DateUtil.getCurrentTime() + " 0" + hour;
        }
        return DateUtil.getDateByString() + " " + hour;
    }

    /**
     * 获取当前时间一个小时前
     *
     * @return 2019-08-27 16
     */
    public static String getCurrentHourBefore() {
        GregorianCalendar calendar = new GregorianCalendar();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour > 0) {
            hour = calendar.get(Calendar.HOUR_OF_DAY) - 1;
            if (hour < 10) {
                return DateUtil.getDateByString() + " 0" + hour;
            }
            return DateUtil.getDateByString() + " " + hour;
        }
        //获取当前日期前一天
        return DateUtil.getBeforeDay() + " " + 23;
    }

    /**
     * 获取当前日期前一天
     *
     * @return 2019-08-26
     */
    public static String getBeforeDay() {

        SimpleDateFormat sdf = new SimpleDateFormat(SDFDATE);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        return sdf.format(date);
    }


    /**
     * 获取最近七天
     *
     * @return 2019-08-20
     */
    public static String getServen() {
        SimpleDateFormat sdf = new SimpleDateFormat(SDFDATE);

        Calendar c = Calendar.getInstance();

        c.add(Calendar.DATE, -7);

        Date monday = c.getTime();

        String preMonday = sdf.format(monday);

        return preMonday;
    }

    /**
     * 获取最近一个月
     *
     * @return 2019-07-27
     */
    public static String getOneMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat(SDFDATE);

        Calendar c = Calendar.getInstance();

        c.add(Calendar.MONTH, -1);

        Date monday = c.getTime();

        String preMonday = sdf.format(monday);

        return preMonday;
    }

    /**
     * 获取最近三个月
     *
     * @return 2019-05-27
     */
    public static String getThreeMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat(SDFDATE);

        Calendar c = Calendar.getInstance();

        c.add(Calendar.MONTH, -3);

        Date monday = c.getTime();

        String preMonday = sdf.format(monday);

        return preMonday;
    }

    /**
     * 获取最近一年
     *
     * @return 2018-08-27
     */
    public static String getOneYear() {
        SimpleDateFormat sdf = new SimpleDateFormat(SDFDATE);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, -1);
        Date start = c.getTime();
        String startDay = sdf.format(start);
        return startDay;
    }

    /**
     * 获取今年月份数据
     * 说明 有的需求前端需要根据月份查询每月数据,此时后台给前端返回今年共有多少月份
     *
     * @return [1, 2, 3, 4, 5, 6, 7, 8]
     */
    public static List getMonthList() {
        List list = new ArrayList();
        for (int i = 1; i <= month; i++) {
            list.add(i);
        }
        return list;
    }

    /**
     * 返回当前年度季度list
     * 本年度截止目前共三个季度,然后根据1,2,3分别查询相关起止时间
     *
     * @return [1, 2, 3]
     */
    public static List getQuartList() {
        int quart = month / 3 + 1;
        List list = new ArrayList();
        for (int i = 1; i <= quart; i++) {
            list.add(i);
        }
        return list;
    }

    /**
     * 获取几天前的时间
     *
     * @param date
     * @param day
     * @return
     */
    public static Date getDateBefore(Date date, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    /**
     * 获取几天后的时间
     *
     * @param date
     * @param day
     * @return
     */
    public static Date getDateAfter(Date date, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }

    /**
     * 返回n天前开始的时间
     *
     * @param day 天数
     * @return
     */
    public static Date someDayStartBefore(int day) {
        return Date.from(LocalDate.now().minusDays(day).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 返回两个日期中的最大值
     *
     * @param date1
     * @param date2
     * @return
     */
    public static Date max(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return date1 != null ? date1 : date2;
        }

        return date1.before(date2) ? date2 : date1;
    }

    /**
     * 获取date日期hours小时后的时间
     *
     * @param hours
     */
    public static Date getAddDate(Date date, Integer hours) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
        return calendar.getTime();
    }

    /**
     * 获取date日期seconds小时后的时间
     *
     * @param
     */
    public static Date getAddSeconds(Date date, Integer seconds) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.SECOND, seconds);
        return calendar.getTime();
    }

    /**
     * 日期格式化string
     *
     * @param date
     * @param format
     * @return
     */
    public static String getDateString(Date date, String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdfDatetime = new SimpleDateFormat(format);
        return sdfDatetime.format(date);
    }

    /**
     * 获取当天剩余时间 秒
     *
     * @return
     */
    public static Long getTodaySurPlusSeconds() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime end = LocalDateTime.of(now.getYear(), now.getMonth(),
                now.getDayOfMonth(), 23, 59, 59);
        long seconds = Duration.between(now, end).getSeconds();
        return seconds;
    }

    /**
     * String转换为Date
     *
     * @param date
     */
    public static Date getCurrentStringToDate(String date, DateTimeFormatter dtf) {
        if (date == null) {
            return null;
        }
        LocalDateTime localDateTime = LocalDateTime.parse(date, dtf);
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取当前时间返回字符串
     *
     * @param format
     * @return
     */
    public static String getCurrentDateString(String format) {
        SimpleDateFormat sdfDatetime = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        return sdfDatetime.format(calendar.getTime());
    }

    /**
     * 获取当前最早的时间 00:00:00
     *
     * @param date
     * @return
     */
    public static Date getCurrentDateStart(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
        LocalDateTime currentDateStart = LocalDateTime.of(LocalDate.of(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDayOfMonth()), LocalTime.MIN);
        return new Date(currentDateStart.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    }

    /**
     * 获取当前最后的时间 23:59:59
     *
     * @param date
     * @return
     */
    public static Date getCurrentDateEnd(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
        LocalDateTime end = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonth(),
                localDateTime.getDayOfMonth(), 23, 59, 59);
        return new Date(end.toInstant(ZoneOffset.of("+8")).toEpochMilli() - 1);
    }

    /**
     * 将给定时间增加day天
     *
     * @param date
     * @param day
     * @return
     */
    public static Date plusDay(Date date, Long day) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault()).plusDays(day);
        return new Date(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    }

    /**
     * 将给定时间减少day天
     *
     * @param date
     * @param day
     * @return
     */
    public static Date minusDays(Date date, Long day) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault()).minusDays(day);
        return new Date(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    }

    /**
     * 将当前时间减少hours小时
     *
     * @param hours
     * @return
     */
    public static Date minusHours(Long hours) {
        LocalDateTime dateTime = LocalDateTime.now().minusHours(1L);
        return new Date(dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    }

    /**
     * 两个时间相差多少秒
     *
     * @param starttime 时间参数 1 格式:1990-01-01 12:00:00
     * @param endtime   时间参数 2 格式:2009-01-01 12:00:00
     * @return Long 返回值为:一共多少秒
     */
    public static Long getDistanceTime(Date starttime, Date endtime) throws Exception {
        if (endtime == null) {
            endtime = new Date();
        }
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long totalsec = 0;
        long time1 = starttime.getTime();
        long time2 = endtime.getTime();
        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        totalsec = sec + (min * 60) + (hour * 60 * 60) + (day * 24 * 60 * 60);
        return totalsec;
    }

    /**
     * 将分秒清零
     *
     * @param date
     * @return
     */
    public static Date removeTimeToZero(Date date, Boolean flag) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date);
        // 将分秒,毫秒域清零
        if (flag) {
            cal1.set(Calendar.HOUR_OF_DAY, 0);
        }
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        return cal1.getTime();
    }
}