【java工具类-时间与日期】获取俩个日期的相差天数日期格式化日期类型转换Date转化为JDK的LocalDate 格式的日期工具类处理日期类型与字符串互转计算俩个日期时分秒

目录

1、距离今天的日期天数

2、在日志监控耗时经常使用的计时器,到毫秒级我们使用计时器

 3、日期的格式化

获取系统时间,格式 yyyy-MM-dd HH:mm:ss

获取字符串系统时间,格式 yyyyMMddHH:mm:ss

时间格式化,字符串与2021年1月15日23:37:50时间格式互相转换

格式化时间,Date转化为String字符串

返回时间段内俩个时间节点相差的所有小时

获取两个日期之间周数列表,俩个日期相差的直接所有周总数

获取两个日期之间相差多少个月 月数列表

获取某一天的开始时间

获取某一天的结束时间

获取俩个时间点的差值转换为分钟或者秒

 获取俩个时间点的差值转换为分钟或者秒

 

全部的工具类,可以直接作为参考,


 

前言:

工作或者使用中java处理日期是经常遇到的问题,所以我们要对Date类型的处理进行架构,能够使之复用。

比如说实现下面的工具类;

又比如说使用功能jdk8版本的获取俩个日期的时间;YYYY-MM-DD这种格式日期的相隔时间;

1、距离今天的日期天数

   public static final String format1 = "yyyy-MM-dd";
    public static final String format2 = "yyyy-MM-dd HH:mm:ss";
    public static final String format3 = "yyyyMMddHHmmss";
    public static final String format4 = "yyyyMMdd";
    public static final String format5 = "yyyy/MM/dd HH";
    public static final String format6 = "yyyy/MM/dd";
    public static final String format7 = "yyyy-MM";
    public static final String format8 = "yyyyMM";
    public static final String format9 = "yyyy/ww";
    public static final String format10 = "yyyy/MM";
 

  可以直接计算出来,距离今天有多久了,一共有多少天

 

/**
 *jdk8版本中进行俩个时间节点的相差天数
 *   与今天日期对比
 * @return
 */
public static Integer getPeriodDays(String  oneDateStr) {
    LocalDate   startLocalDate = LocalDate.parse(oneDateStr, DateUtil.FORMATTERS_1);
    LocalDate   todayLocalDate = LocalDate.now();
    Long  diffDays=Duration.between(startLocalDate.atStartOfDay(),todayLocalDate.atStartOfDay()).toDays();
    return diffDays.intValue() ;
}

2、在日志监控耗时经常使用的计时器,到毫秒级我们使用计时器

Instant startPostTime = Instant.now();
String ID = httpPostManager.sendGet(SysConfig.CHECK_ID);
Instant endPostTime = Instant.now();
long peridMillis = Duration.between(startPostTime, endPostTime).toMillis();
log.error("当前返回id={}, 请求访问返回结果耗时{}毫秒", Id, peridMillis);

 3、日期的格式化

 /**

获取系统时间,格式 yyyy-MM-dd HH:mm:ss

     *
     * @return  字符串
     */
    public static String getSysDateToString() {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_DATETIME);
        return df.format(new Date());
    }

    /**

获取字符串系统时间,格式 yyyyMMddHH:mm:ss

     *
     * @return
     */
    public static String getSysDate() {
        SimpleDateFormat df = new SimpleDateFormat(YYYYMMDDHHMMSSS);
        return df.format(new Date());
    }

    /**

时间格式化,字符串与2021年1月15日23:37:50时间格式互相转换

     *
     * @return
     */
    public static String getDateFormat(Date date, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }


格式化时间,Date转化为String字符串


     */
    public static String format(Date date, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }

 /**


返回时间段内俩个时间节点相差的所有小时


     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getHours(Date startTime, Date endTime) {
        // 返回的日期集合
        List<String> hours = Lists.newArrayList();
        DateFormat dateFormat = new SimpleDateFormat(format6);
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(startTime);
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(endTime);
        while (tempStart.before(tempEnd)) {
            String day = dateFormat.format(tempStart.getTime());
            for (String hour : HOURS_DAY) {
                hours.add(day + " " + hour);
            }
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return hours;
    }

    /**
     *

获取两个日期之间周数列表,俩个日期相差的直接所有周总数


     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getWeeks(Date startTime, Date endTime) {
        List<String> weeks = Lists.newArrayList();
        Calendar start = Calendar.getInstance();
        start.setFirstDayOfWeek(Calendar.MONDAY);
        start.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setFirstDayOfWeek(Calendar.MONDAY);
        end.setTime(endTime);
        while (start.before(end)) {
            weeks.add(FORMATTERS_9.format(start.getTime()));
            start.add(Calendar.WEEK_OF_YEAR, 1);
        }
        return weeks;
    }

    /**


获取两个日期之间相差多少个月 月数列表


     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getMonths(Date startTime, Date endTime) {
        List<String> weeks = Lists.newArrayList();
        Calendar start = Calendar.getInstance();
        start.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        while (start.before(end)) {
            weeks.add(FORMATTERS_10.format(start.getTime()));
            start.add(Calendar.MONTH, 1);
        }
        return weeks;
    }

    /**

获取某一天的开始时间


     *
     * @param currentDate
     * @return
     */
    public static String getStartTime(Date currentDate) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_DATETIME);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return df.format(calendar.getTime());
    }

    /**
     *

获取某一天的结束时间


     *
     * @param currentDate
     * @return
     */
    public static String getEndTime(Date currentDate) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_DATETIME);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        return df.format(calendar.getTime());
    }

    public static Date getEndDate(Date currentDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        return calendar.getTime();
    }

    /***

获取俩个时间点的差值转换为分钟或者秒


     * @param startDate
     * @param currentDate
     * @return
     */
    public static String getPeriodDiffTime(Date startDate, Date currentDate) {
        if (startDate != null && currentDate != null) {
            long minuteMillionNum = 1000 * 60;
            // 获得两个时间的毫秒时间差异
            long diff = currentDate.getTime() - startDate.getTime();
            // 计算差多少秒
            long millionminute = diff / 1000;
            // 计算差多少分钟
            long minute = diff / minuteMillionNum;
            if (minute > 0) {
                millionminute = (diff - minute * minuteMillionNum) / 1000;
                return minute + "分钟" + millionminute + "秒";
            } else {
                return Math.abs(millionminute) + "秒";
            }
        }
        return "未知";
    }

    /***


 获取俩个时间点的差值转换为分钟或者秒


     * @param startDate
     * @param currentDate
     * @return
     */
    public static Long getPeriodDiffTimeNum(Date startDate, Date currentDate) {
        if (startDate != null && currentDate != null) {
            // 获得两个时间的毫秒时间差异
            long diff = currentDate.getTime() - startDate.getTime();
            // 计算差多少秒
            long millionminute = diff / 1000;
            return Math.abs(millionminute);
        }
        return 0L;
    }

 

全部的工具类,可以直接作为参考,

 



import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 脚踏实地的做好本职工作,积累
 * @date 2020/12/3
 */
public class DateUtil {
    /**
     * 时间格式:"yyyy-MM-dd HH:mm:ss"
     */
    public final static String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";

    /**
     * 时间格式:"yyyy-MM-dd HH:mm:ss"
     */
    public final static String YYYYMMDDHHMMSSS = "yyyyMMddHHmmsss";

    public final static String[] HOURS_DAY = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11",
            "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};

    public static final String format1 = "yyyy-MM-dd";
    public static final String format2 = "yyyy-MM-dd HH:mm:ss";
    public static final String format3 = "yyyyMMddHHmmss";
    public static final String format4 = "yyyyMMdd";
    public static final String format5 = "yyyy/MM/dd HH";
    public static final String format6 = "yyyy/MM/dd";
    public static final String format7 = "yyyy-MM";
    public static final String format8 = "yyyyMM";
    public static final String format9 = "yyyy/ww";
    public static final String format10 = "yyyy/MM";

    public static final DateTimeFormatter FORMATTERS_1 = DateTimeFormatter.ofPattern(format1);

    public static final DateTimeFormatter FORMATTERS_2 = DateTimeFormatter.ofPattern(format2);

    public static final DateTimeFormatter FORMATTERS_4 = DateTimeFormatter.ofPattern(format4);

    public static final DateTimeFormatter FORMATTERS_7 = DateTimeFormatter.ofPattern(format7);

    public static final DateTimeFormatter FORMATTERS_8 = DateTimeFormatter.ofPattern(format8);
    public static final SimpleDateFormat FORMATTERS_9 = new SimpleDateFormat(format9);
    public static final SimpleDateFormat FORMATTERS_10 = new SimpleDateFormat(format10);


    /**
     * 获取系统时间,格式 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getSysDateToString() {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_DATETIME);
        return df.format(new Date());
    }



    /**
     * 获取系统时间,格式 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getSysDate() {
        SimpleDateFormat df = new SimpleDateFormat(YYYYMMDDHHMMSSS);
        return df.format(new Date());
    }

    /**
     * 时间格式化
     *
     * @return
     */
    public static String getDateFormat(Date date, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

    /**
     * 格式化时间
     */
    public static String format(Date date, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }

    /**
     * 今天日期
     */
    public static String getToday() {
        return format(new Date(), format1);
    }

    /**
     * 时间字符串转Date
     *
     * @param dateStr
     * @param format
     * @return
     */
    public static Date parse(String dateStr, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 前一天日期
     */
    public static String previousDay() {
        return previousNDay(1);
    }

    /**
     * 几一天日期
     */
    public static String previousNDay(int n) {
        SimpleDateFormat sdf = new SimpleDateFormat(format1);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -n);
        Date preDay = c.getTime();
        String preDayStr = sdf.format(preDay);
        return preDayStr;
    }

    /**
     * 获取当天24点时间
     *
     * @return
     */
    public static Long getTimesNight() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime().getTime();
    }

    /**
     * 获得当天零时零分零秒
     *
     * @return
     */
    public static Date todayHourDate(int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获得昨天的时间点
     *
     * @return
     */
    public static Date yesterdayHourDate(int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取五周前的星期一零点零分零秒
     *
     * @return
     */
    public static Date getSixWeekAgoTime() {
        Calendar calendar = Calendar.getInstance();
        // 设置为本周的星期日
        calendar.set(Calendar.DAY_OF_WEEK, 1);
        calendar.add(Calendar.WEEK_OF_MONTH, -5);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取五个月前的1号零点零分零秒
     *
     * @return
     */
    public static Date getSixMonthAgoTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -5);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 返回时间段内所有日期天数
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getDays(Date startTime, Date endTime) {
        // 返回的日期集合
        List<String> days = Lists.newArrayList();
        DateFormat dateFormat = new SimpleDateFormat(format6);
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(startTime);
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(endTime);
        while (tempStart.before(tempEnd)) {
            days.add(dateFormat.format(tempStart.getTime()));
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return days;
    }

    /**
     * 返回时间段内所有小时
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getHours(Date startTime, Date endTime) {
        // 返回的日期集合
        List<String> hours = Lists.newArrayList();
        DateFormat dateFormat = new SimpleDateFormat(format6);
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(startTime);
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(endTime);
        while (tempStart.before(tempEnd)) {
            String day = dateFormat.format(tempStart.getTime());
            for (String hour : HOURS_DAY) {
                hours.add(day + " " + hour);
            }
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return hours;
    }

    /**
     * 获取两个日期之间周数列表
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getWeeks(Date startTime, Date endTime) {
        List<String> weeks = Lists.newArrayList();
        Calendar start = Calendar.getInstance();
        start.setFirstDayOfWeek(Calendar.MONDAY);
        start.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setFirstDayOfWeek(Calendar.MONDAY);
        end.setTime(endTime);
        while (start.before(end)) {
            weeks.add(FORMATTERS_9.format(start.getTime()));
            start.add(Calendar.WEEK_OF_YEAR, 1);
        }
        return weeks;
    }

    /**
     * 获取两个日期之间月数列表
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getMonths(Date startTime, Date endTime) {
        List<String> weeks = Lists.newArrayList();
        Calendar start = Calendar.getInstance();
        start.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        while (start.before(end)) {
            weeks.add(FORMATTERS_10.format(start.getTime()));
            start.add(Calendar.MONTH, 1);
        }
        return weeks;
    }

    /**
     * 获取某一天的开始时间
     *
     * @param currentDate
     * @return
     */
    public static String getStartTime(Date currentDate) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_DATETIME);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return df.format(calendar.getTime());
    }

    /**
     * 获取某一天的结束时间
     *
     * @param currentDate
     * @return
     */
    public static String getEndTime(Date currentDate) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_DATETIME);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        return df.format(calendar.getTime());
    }

    public static Date getEndDate(Date currentDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        return calendar.getTime();
    }

    /***
     * 获取俩个时间点的差值转换为分钟或者秒
     * @param startDate
     * @param currentDate
     * @return
     */
    public static String getPeriodDiffTime(Date startDate, Date currentDate) {
        if (startDate != null && currentDate != null) {
            long minuteMillionNum = 1000 * 60;
            // 获得两个时间的毫秒时间差异
            long diff = currentDate.getTime() - startDate.getTime();
            // 计算差多少秒
            long millionminute = diff / 1000;
            // 计算差多少分钟
            long minute = diff / minuteMillionNum;
            if (minute > 0) {
                millionminute = (diff - minute * minuteMillionNum) / 1000;
                return minute + "分钟" + millionminute + "秒";
            } else {
                return Math.abs(millionminute) + "秒";
            }
        }
        return "未知";
    }

    /***
     * 获取俩个时间点的差值转换为分钟或者秒
     * @param startDate
     * @param currentDate
     * @return
     */
    public static Long getPeriodDiffTimeNum(Date startDate, Date currentDate) {
        if (startDate != null && currentDate != null) {
            // 获得两个时间的毫秒时间差异
            long diff = currentDate.getTime() - startDate.getTime();
            // 计算差多少秒
            long millionminute = diff / 1000;
            return Math.abs(millionminute);
        }
        return 0L;
    }

    public enum Quarter {

        /**
         * 第一季度
         */
        FIRST(1, "1Q"),
        /**
         * 第二季度
         */
        SECOND(4, "2Q"),
        /**
         * 第三季度
         */
        THIRD(7, "3Q"),
        /**
         * 第四季度
         */
        FOURTH(10, "4Q");

        /**
         * 季度的第一天
         */
        private Integer minMonth;

        /**
         * 季度名称
         */
        private String name;

        Quarter(Integer minMonth, String name) {
            this.minMonth = minMonth;
            this.name = name;
        }

        public Integer getMinMonth() {
            return minMonth;
        }

        public void setMinMonth(Integer minMonth) {
            this.minMonth = minMonth;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class QuarterOfYearQuery implements TemporalQuery<Quarter> {
        @Override
        public Quarter queryFrom(TemporalAccessor temporal) {
            LocalDate now = LocalDate.from(temporal);

            if (now.isBefore(now.with(Month.APRIL).withDayOfMonth(1))) {
                return Quarter.FIRST;
            } else if (now.isBefore(now.with(Month.JULY).withDayOfMonth(1))) {
                return Quarter.SECOND;
            } else if (now.isBefore(now.with(Month.OCTOBER).withDayOfMonth(1))) {
                return Quarter.THIRD;
            } else {
                return Quarter.FOURTH;
            }
        }
    }

    public static LocalDateTime parse(Date date) {
        if (date == null) {
            return null;
        }
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    public static LocalDateTime parse(String datestr) {
        if (StringUtils.isNotBlank(datestr)) {
            return LocalDateTime.parse(datestr, DateTimeFormatter.ofPattern(format2));
        }
        return null;

    }

    public static Date toDate(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static Long toLong(LocalDateTime localDateTime) {
        if (null == localDateTime) {
            return null;
        }
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 获取两个时间间隔的天数
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 间隔的天数
     */
    public static double getIntervalDays(Date startDate, Date endDate) {
        double interPerid = endDate.getTime() - startDate.getTime();
        double oneDay = 60 * 60 * 24 * 1000;
        if (interPerid < 0) {
            double resultAbs=Math.abs(interPerid / oneDay);
            double result = Math.round(resultAbs);
            if(resultAbs>result){
                return -(result+1);
            }
            return -result;
        }
        return Math.round(interPerid / oneDay);
    }

    /**
     * 增加日期的秒钟。失败返回null。
     *
     * @param date         日期字符串
     * @param secondAmount 增加数量。可为负数
     * @return 增加秒钟后的日期字符串
     */
    public static String addSecond(String date, int secondAmount) {
        return addInteger(date, Calendar.SECOND, secondAmount);
    }

    /**
     * 增加日期中某类型的某数值。如增加日期
     *
     * @param date     日期字符串
     * @param dateType 类型
     * @param amount   数值
     * @return 计算后日期字符串
     */
    private static String addInteger(String date, int dateType, int amount) {

        Date myDate = toDate(parse(date));
        myDate = addInteger(myDate, dateType, amount);
        String dateString = format(myDate, FORMAT_DATETIME);

        return dateString;
    }

    /**
     * 增加日期中某类型的某数值。如增加日期
     *
     * @param date     日期
     * @param dateType 类型
     * @param amount   数值
     * @return 计算后日期
     */
    private static Date addInteger(Date date, int dateType, int amount) {
        Date myDate = null;
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(dateType, amount);
            myDate = calendar.getTime();
        }
        return myDate;
    }

    public static Long getIntervalDays(String startDateStr, String endDateStr) {

        Date startDate = parse(startDateStr, FORMAT_DATETIME);
        Date endDate = parse(endDateStr, FORMAT_DATETIME);
        if (null == startDate || null == endDate) {
            return 0L;
        }
        Double result = getIntervalDays(startDate, endDate);
        return Long.valueOf(result.longValue());
    }
    /**
     * 获取date之前past日的日期
     * @param date
     * @param past
     * @return
     */
    public static Date getPastDate(Date date, int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        return calendar.getTime();
    }

    /**
     * 获取date之后的第past天的日期
     * @param date
     * @param future
     * @return
     */
    public static Date getFutureDate(Date date, int future) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + future);
        return calendar.getTime();
    }

    /**
     *将 localtime 转成date
     * @param localdatetime
     * @return
     */
    public static Date LocalDateTimeToDate(LocalDateTime  localdatetime) {

        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt =  localdatetime.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取系统时间,格式 yyyy-MM-dd
     *
     * @return
     */
    public static String getNowDateToYYYYMMDD() {
        SimpleDateFormat df = new SimpleDateFormat(format1);
        return df.format(new Date());
    }


    /**
     *jdk8版本中进行俩个时间节点的相差天数
     *   与今天日期对比
     * @return
     */
    public static Integer getPeriodDays(String  oneDateStr) {
        LocalDate   startLocalDate = LocalDate.parse(oneDateStr, DateUtil.FORMATTERS_1);
        LocalDate   todayLocalDate = LocalDate.now();
        Long  diffDays=Duration.between(startLocalDate.atStartOfDay(),todayLocalDate.atStartOfDay()).toDays();

        return diffDays.intValue() ;
    }


    public static void main(String[] args) {
//        String startDateStr = "2020-07-30 00:00:00";
        String startDateStr = "2020-08-14 00:00:00";
        String endDateSTr = "2020-08-06 16:44:00";
        System.out.println(getIntervalDays(startDateStr, endDateSTr));
        System.out.println("距离今天"+getPeriodDays("2020-09-02"));
        //8





    }
}


运算结果展示:
-8
距离今天0


 

君子志邦 CSDN认证博客专家 Python TensorFlow
java工作5年+,从一个java新手,目前已经成长为技术专家,这一路走来真的很辛苦,目前在杭州,也偶尔做技术面试,主要做金融行业软件相关,java全栈,加班不多所以可以偶尔的发发自己的帖子,总结下自己的经验!分享下心得!加油,会越来越好的!让这世界更加美好我们一起努力!
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__ 返回首页
实付 29.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值