美文网首页spring boot
java时间工具类

java时间工具类

作者: 小石读史 | 来源:发表于2020-01-19 08:27 被阅读0次
package com.yql.mytest.utils;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtils  {

    /**
     * 返回指定月数的日期
     *
     * @param date
     * @param month
     * @return
     * @author guos
     * @date 2019/4/13 16:26
     **/
    public static Date getExpireMonth(Date date, int month) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, month);
        return cal.getTime();
    }

    /**
     * 返回指定天数的日期
     *
     * @param date
     * @param day
     * @return
     */
    public static Date getExpireDate(Date date, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH, day);
        return cal.getTime();
    }

    /**
     * 返回指定分钟后的日期
     * @param date
     * @param minute
     * @return
     */
    public static Date getExpireMinute(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, minute);
        return cal.getTime();
    }


    /**
     * <p>Title: getExpireHour</p>
     * <p>Description: 返回指定日期多少小时后的时间</p>
     *
     * @param date
     * @param hour
     * @return
     * @author yql
     */
    public static Date getExpireHour(Date date, int hour) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR_OF_DAY, hour);
        return cal.getTime();
    }


    /**
     * 根据指定参数kind,获取指定类型的Date日期(年月日)
     *
     * @param kind 指定参数
     * @return Date 指定类型的Date
     */
    public static Date getFormatDate(Date date, int kind) {
        String currentDateStr = formatDate(date, kind);
        return toDate(currentDateStr, kind);
    }

    /**
     * 根据kind输出string格式
     *
     * @param date
     * @param kind
     * @return
     */
    public static String formatDate(Date date, int kind) {
        SimpleDateFormat sdf = new SimpleDateFormat(getDateFormat(kind));
        return sdf.format(date);
    }

    public static String formatCurrentDate(int kind) {
        SimpleDateFormat sdf = new SimpleDateFormat(getDateFormat(kind));
        return sdf.format(new Date());
    }

    public static Date toDate(String dateText, int kind) {
        String format = getDateFormat(kind);
        if (dateText == null) {
            return null;
        }
        DateFormat df = null;
        try {
            if (format == null) {
                df = new SimpleDateFormat();
            } else {
                df = new SimpleDateFormat(format);
            }
            df.setLenient(false);
            return df.parse(dateText);
        } catch (ParseException e) {
            return null;
        }
    }

    private static String getDateFormat(int kind) {
        String[] format = {"yyyy-MM-dd", // 0
                "yyyy-MM-dd HH:mm:ss", // 1
                "yyyy",// 2
                "M",// 3
                "dd", // 4
                "yyyy年M月d日H点m分", // 5
                "yyyy年M月d日", // 6
                "H点m分", // 7
                "yyyy/MM/dd HH:mm", // 8
                "HH",// 9
                "mm",// 10
                "yyyyMMdd", // 11
                "yyyyMMddHHmmss", // 12
                "yyyy-MM-dd 23:59:59", // 13
                "HH:mm:ss", // 14
                "yyyy/MM/dd HH:mm:ss", // 15
                "yyyy/MM/dd HH:mm",//16
                "HHmmss",//17,
                "HH:mm:ss", //18
                "mmss", //19
                "HH:mm", //20
                "yyyy-MM-dd HH:mm", //21
                "yyyyMMddHHmm", // 22
        };
        return format[kind];
    }

    /**
     * 计算两个日期的秒数之差
     *
     * @param oldDate
     * @param newDate
     * @return
     */
    public static long secondsBetween(Date oldDate, Date newDate) {
        long between = (newDate.getTime() / 1000 - oldDate.getTime() / 1000);//除以1000是为了转换成秒
        return between;
    }

    /**
     * 计算传入时间距离24点剩余秒数
     *
     * @param currentDate
     * @return
     */
    public static Integer getRemainSecondsOneDay(Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
                .withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }




    /**
     * 获得某天最小时间 2018-01-01 00:00:00
     *
     * @param date
     * @return
     */

    public static Date getMinTimeOfDay(Date date) {
        if (date == null) {
            return null;
        }
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),
                ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获得某天最大时间 2018-01-01 23:59:59
     *
     * @param date
     * @return
     */
    public static Date getMaxTimeOfDay(Date date) {
        if (date == null) {
            return null;
        }
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),
                ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }


    /**
     * 判断两个时间段的交集
     *
     * @param leftStartDate
     * @param leftEndDate
     * @param rightStartDate
     * @param rightEndDate
     * @return
     * @author guos
     * @date 2019/7/16 14:57
     **/
    public static boolean isDateCross(Date leftStartDate, Date leftEndDate, Date rightStartDate, Date rightEndDate) {
        return
                ((leftStartDate.getTime() >= rightStartDate.getTime())
                        && leftStartDate.getTime() < rightEndDate.getTime())
                        ||
                        ((leftStartDate.getTime() > rightStartDate.getTime())
                                && leftStartDate.getTime() <= rightEndDate.getTime())
                        ||
                        ((rightStartDate.getTime() >= leftStartDate.getTime())
                                && rightStartDate.getTime() < leftEndDate.getTime())
                        ||
                        ((rightStartDate.getTime() > leftStartDate.getTime())
                                && rightStartDate.getTime() <= leftEndDate.getTime());
    }


    /**
     * 获取本月第一天
     * @return
     */
    public static Date getMindate(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));

        return calendar.getTime();
    }

    /**
     * 获取本月最后一天
     * @return
     */
    public static Date getMaxdate(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return calendar.getTime();
    }

    /**
     * 获取当月开始时间戳
     *
     * @param timeStamp 毫秒级时间戳
     * @param timeZone  如 GMT+8:00
     * @return
     */
    public static Long getMonthStartTime(Long timeStamp, String timeZone) {
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(timeStamp);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    /**
     * 获取当月的结束时间戳
     *
     * @param timeStamp 毫秒级时间戳
     * @param timeZone  如 GMT+8:00
     * @return
     */
    public static Long getMonthEndTime(Long timeStamp, String timeZone) {
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        calendar.setTimeInMillis(timeStamp);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));// 获取当前月最后一天
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }

    public static void main(String[] a){
        System.out.println("当天时间3天后的时间:"+DateUtils.getExpireDate(new Date(),3));

        Long nowTime = new Date().getTime();
        Long monthStartTime = DateUtils.getMonthStartTime(nowTime,"GMT+8:00");
        System.out.println("传入时间当月的开始时间monthStartTime:"+monthStartTime);
        Long monthEndTime = DateUtils.getMonthEndTime(nowTime,"GMT+8:00");
        System.out.println("传入时间当月的结束时间monthEndTime:"+monthEndTime);

        String monthStartTimeStr = DateUtils.formatDate(new Date(monthStartTime),1);
        System.out.println("传入时间当月的开始时间monthStartTimeStr:"+monthStartTimeStr);
        String monthEndTimeStr = DateUtils.formatDate(new Date(monthEndTime),12);
        System.out.println("传入时间当月的结束时间monthEndTimeStr:"+monthEndTimeStr);

        Date minDate = DateUtils.getMinTimeOfDay(new Date());
        System.out.println("传入时间当天的最小时间minDate:"+minDate);

        Date maxDate = DateUtils.getMaxTimeOfDay(new Date());
        System.out.println("传入时间当天的最大时间maxDate:"+maxDate);

        System.out.println("距离当天24点剩余秒数:"+DateUtils.getRemainSecondsOneDay(new Date()));
    }

}

执行结果:
当天时间3天后的时间:Mon Jan 20 15:37:38 CST 2020
传入时间当月的开始时间monthStartTime:1577808000000
传入时间当月的结束时间monthEndTime:1580486399999
传入时间当月的开始时间monthStartTimeStr:2020-01-01 00:00:00
传入时间当月的结束时间monthEndTimeStr:20200131235959
传入时间当天的最小时间minDate:Fri Jan 17 00:00:00 CST 2020
传入时间当天的最大时间maxDate:Fri Jan 17 23:59:59 CST 2020
距离当天24点剩余秒数:30141

相关文章

网友评论

    本文标题:java时间工具类

    本文链接:https://www.haomeiwen.com/subject/mbnczctx.html