jdk8时间工具类

package gdt.lego.util;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.List;


/**
 * @author kk
 */
public class DateUtil4Jdk8 {

    private static final Logger LOG = LoggerFactory.getLogger(DateUtil4Jdk8.class);

    public final static String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";

    public final static String DATE_FORMAT_YMD = "yyyyMMdd";

    public final static String DATE_FORMAT_YMD_LINE = "yyyy-MM-dd";

    public final static String DATE_FORMAT_DEFAULT_WITH_SSS = "yyyy-MM-dd HH:mm:ss:SSS";

    public final static Integer DAY_ONE = 1;
    public final static Integer DAY_TWO = 2;

    public final static Integer DAY_SEVEN = 7;


    /**
     * 时间毫秒转换为String(yyyy-MM-dd HH:mm:ss)
     *
     * @param millisecond
     * @return
     */
    public static String milliTimeToString(final Long millisecond) {
        if (null == millisecond) {
            return null;
        }
        return localDateTime2String(date2LocalDateTime(new Date(millisecond)), DATE_FORMAT_DEFAULT);
    }

    /**
     * 时间秒转换为String(yyyy-MM-dd HH:mm:ss)
     *
     * @param secondTime
     * @return
     */
    public static String secondTimeToString(final Long secondTime) {
        if (null == secondTime) {
            return null;
        }
        return localDateTime2String(date2LocalDateTime(new Date(secondTime * 1000)), DATE_FORMAT_DEFAULT);
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDateTime
     * @return
     */
    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        Assert.notNull(localDateTime, "localDateTime not null.");
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date转换为LocalDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date) {
        Assert.notNull(date, "date not null.");
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * Date转换为LocalDate
     *
     * @param date
     * @return
     */
    public static LocalDate date2LocalDate(Date date) {
        Assert.notNull(date, "date not null.");
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * Date转换为LocalTime
     *
     * @param date
     * @return
     */
    public static LocalTime date2LocalTime(Date date) {
        Assert.notNull(date, "date not null.");
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
    }

    /**
     * 获取当前时间前minusDays天的时间(minusDays为正数为当前天之前,为负数为当前天之后,为0时为当前天)
     *
     * @param minusDays
     * @return
     */
    public static LocalDateTime getLocalDateTime4MinusDays(long minusDays) {
        return LocalDateTime.now().minusDays(minusDays);
    }

    /**
     * 获取当前时间前minusDays天的时间(minusDays为正数为当前天之前,为负数为当前天之后,为0时为当前天)
     *
     * @param minusDays
     * @return
     */
    public static LocalDate getLocalDate4MinusDays(long minusDays) {
        return LocalDate.now().minusDays(minusDays);
    }

    /**
     * 获取当前时间后plusDays天的时间(plusDays为正数为当前天之后,为负数为当前天之前,为0时为当前天)
     *
     * @param plusDays
     * @return
     */
    public static LocalDateTime getLocalDateTime4PlusDays(long plusDays) {
        return LocalDateTime.now().plusDays(plusDays);
    }


    /**
     * 将指定LocalDateTime转换为String,暂时只支持(yyyy-MM-dd HH:mm:ss,yyyyMMdd,yyyy-MM-dd)
     *
     * @param localDateTime
     * @param dateFormat
     * @return
     */
    public static String localDateTime2String(LocalDateTime localDateTime, String dateFormat) {
        Assert.notNull(localDateTime, "localDateTime not null.");
        Assert.hasLength(dateFormat, "dateFormat not null.");
        if (dateFormat.equals(DATE_FORMAT_YMD))
            return localDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT_YMD));

        if (dateFormat.equals(DATE_FORMAT_DEFAULT))
            return localDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT));

        if (dateFormat.equals(DATE_FORMAT_YMD_LINE))
            return localDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT_YMD_LINE));

        throw new RuntimeException("localDateTime2String dateFormat check failed.");

    }


    /**
     * 将当前LocalDateTime转换为String,暂时只支持(yyyy-MM-dd HH:mm:ss,yyyyMMdd,yyyy-MM-dd)
     *
     * @param dateFormat
     * @return
     */
    public static String currentLocalDateTime2String(String dateFormat) {
        Assert.hasLength(dateFormat, "dateFormat not null.");
        LocalDateTime now = LocalDateTime.now();
        if (dateFormat.equals(DATE_FORMAT_YMD))
            return now.format(DateTimeFormatter.ofPattern(DATE_FORMAT_YMD));

        if (dateFormat.equals(DATE_FORMAT_DEFAULT))
            return now.format(DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT));

        if (dateFormat.equals(DATE_FORMAT_YMD_LINE))
            return now.format(DateTimeFormatter.ofPattern(DATE_FORMAT_YMD_LINE));

        throw new RuntimeException("localDateTime2String dateFormat check failed.");

    }


    /**
     * dateString转换为Date,暂时只支持(yyyy-MM-dd HH:mm:ss,yyyyMMdd)
     *
     * @param dateString
     * @param dateFormat
     * @return
     */
    public static Date dateString2Date(String dateString, String dateFormat) {
        Assert.hasLength(dateString, "date not null.");
        Assert.hasLength(dateFormat, "dateFormat not null.");
        if (dateFormat.equals(DATE_FORMAT_YMD) || dateFormat.equals(DATE_FORMAT_YMD_LINE)) {
            try {
                DateTimeFormatter df;
                if (dateFormat.equals(DATE_FORMAT_YMD)) {
                    df = DateTimeFormatter.ofPattern(DATE_FORMAT_YMD);
                } else {
                    df = DateTimeFormatter.ofPattern(DATE_FORMAT_YMD_LINE);
                }
                LocalDate ldt = LocalDate.parse(dateString, df);
                ZoneId zoneId = ZoneId.systemDefault();
                ZonedDateTime zdt = ldt.atStartOfDay(zoneId);
                return Date.from(zdt.toInstant());
            } catch (Exception e) {
                LOG.error("Exception when dateString2Date {}", e.fillInStackTrace());
                throw new RuntimeException("dateString2Date parse failed.");
            }
        }

        if (dateFormat.equals(DATE_FORMAT_DEFAULT)) {
            try {
                DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT);
                LocalDateTime ldt = LocalDateTime.parse(dateString, df);
                return localDateTime2Date(ldt);
            } catch (Exception e) {
                LOG.error("Exception when dateString2Date {}", e.fillInStackTrace());
                throw new RuntimeException("dateString2Date parse failed.");
            }
        }
        throw new RuntimeException("dateString2Date dateFormat check failed.");

    }

    /**
     * dateString转换为LocalDateTime,暂时只支持(yyyy-MM-dd HH:mm:ss)
     *
     * @param dateString
     * @param dateFormat
     * @return
     */
    public static LocalDateTime dateString2LocalDateTime(String dateString, String dateFormat) {
        Assert.hasLength(dateString, "date not null.");
        Assert.hasLength(dateFormat, "dateFormat not null.");
        if (dateFormat.equals(DATE_FORMAT_DEFAULT)) {
            try {
                DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT);
                return LocalDateTime.parse(dateString, df);
            } catch (Exception e) {
                LOG.error("Exception when dateString2LocalDateTime {}", e.fillInStackTrace());
                throw new RuntimeException("dateString2LocalDateTime parse failed.");
            }
        }
        throw new RuntimeException("dateString2LocalDateTime dateFormat check failed.");

    }


    /**
     * 将"2018-10-18 17:50:07:903" 此格式时间去除毫秒
     *
     * @param dateString
     * @return
     */
    public static String defaultDateStringRemoveSSS(final String dateString) {
        try {
            final DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT_WITH_SSS);
            final LocalDateTime ldt = LocalDateTime.parse(dateString, df);
            return LocalDateTime.of(ldt.getYear(), ldt.getMonth(), ldt.getDayOfMonth(), ldt.getHour(), ldt.getMinute(), ldt.getSecond())
                    .format(DateTimeFormatter.ofPattern(DATE_FORMAT_DEFAULT));
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 判断当前时间是否为当月第一天
     *
     * @return
     */
    public static Boolean isFirstDayWithMonth() {
        return Objects.equal(LocalDate.now().getDayOfMonth(), DAY_ONE);
    }

    /**
     * 判断当前时间是否为本周第selectDay天(1<=selectDay<=7)
     *
     * @return
     */
    public static Boolean isSelectDayWithWeek(final Integer selectDay) {
        if (selectDay < DAY_ONE || selectDay > DAY_SEVEN) {
            throw new RuntimeException("isSelectDayWithWeek selectDay must be 1<=selectDay<=7.");
        }
        final TemporalField fieldIso = WeekFields.of(DayOfWeek.MONDAY, selectDay).dayOfWeek();
        final LocalDate now = LocalDate.now();
        final LocalDate firstDayWithWeek = now.with(fieldIso, selectDay);
        return firstDayWithWeek.equals(now);
    }


    /**
     * 判断当前时间前minusDays天的时间是否跟当前时间同一个月份
     *
     * @param minusDays
     * @return
     */
    public static Boolean isEqualsSameMonthWithMinusDays(long minusDays) {
        final LocalDate localDateWithMinusDays = LocalDate.now().minusDays(minusDays);
        final LocalDate now = LocalDate.now();
        return Objects.equal(localDateWithMinusDays.getMonthValue(), now.getMonthValue());
    }

    /**
     * 将字符串"yyyy-MM-dd HH:mm:ss" 转换为秒数
     *
     * @param dateString
     * @return
     */
    public static long dateString2EpochSecond(final String dateString) {
        Assert.hasLength(dateString, "date not null.");
        return dateString2LocalDateTime(dateString, DATE_FORMAT_DEFAULT).toEpochSecond(ZoneOffset.of("+8"));
    }

    /**
     * 将LocalDate转换为Date
     *
     * @param localDate
     * @return
     */
    public static Date localDate2Date(final LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取当前时间整点前hours小时的时间整点数集合
     *
     * @param hours
     * @return
     */
    public static List<LocalDateTime> getLocalDateTimeList4Hours(final long hours) {
        if (hours < 0L) {
            throw new RuntimeException("getLocalDateTimeList4Hours hours must be positive integer.");
        }
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime integralPointNow = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), now.getHour(), 0, 0);
        final LocalDateTime before = integralPointNow.minusHours(hours);
        final List<LocalDateTime> res = Lists.newArrayList();
        for (int i = 0; i <= hours; i++) {
            res.add(before.plusHours(i));
        }
        return res;
    }

    /**
     * 获取当前时间前days天的时间天数集合
     *
     * @param days
     * @return
     */
    public static List<LocalDate> getLocalDateList4Days(final long days) {
        if (days < 0L) {
            throw new RuntimeException("getLocalDateList4Days hours must be positive integer.");
        }
        final LocalDate now = LocalDate.now();
        final LocalDate before = now.minusDays(days);
        final List<LocalDate> res = Lists.newArrayList();
        for (int i = 0; i < days; i++) {
            res.add(before.plusDays(i));
        }
        return res;
    }

    /**
     * 计算{@code startDate}与当前日期的间隔天数
     *
     * @param startDate
     * @return 间隔天数
     */
    public static long until(final LocalDate startDate) {
        return startDate.until(LocalDate.now(), ChronoUnit.DAYS);
    }


    /**
     * 计算{@code startDateTime}与当前时间的间隔分钟
     *
     * @param startDateTime
     * @return 间隔天数
     */
    public static long untilM(final LocalDateTime startDateTime) {
        return LocalDateTime.now().until(startDateTime, ChronoUnit.MINUTES);
    }


    /**
     * 获取某周的开始日期
     *
     * @param offset 0本周,1下周,-1上周,依次类推
     * @return
     */
    public static LocalDate weekStart(int offset) {
        LocalDate localDate = LocalDate.now().plusWeeks(offset);
        return localDate.with(DayOfWeek.MONDAY);
    }

    /**
     * 获取某周的结束日期
     *
     * @param offset 0本周,1下周,-1上周,依次类推
     * @return
     */
    public static LocalDate weekEnd(int offset) {
        LocalDate localDate = LocalDate.now().plusWeeks(offset);
        return localDate.with(DayOfWeek.SUNDAY);
    }

    /**
     * 获取某月的开始日期
     *
     * @param offset 0本月,1下个月,-1上个月,依次类推
     * @return
     */
    public static LocalDate monthStart(int offset) {
        return LocalDate.now().plusMonths(offset).with(TemporalAdjusters.firstDayOfMonth());
    }


    /**
     * 获取某季度的开始日期
     * 季度一年四季, 第一季度:2月-4月, 第二季度:5月-7月, 第三季度:8月-10月, 第四季度:11月-1月
     *
     * @param offset 0本季度,1下个季度,-1上个季度,依次类推
     * @return
     */
    public static LocalDate quarterStart(int offset) {
        final LocalDate date = LocalDate.now().plusMonths(offset * 3);
        //当月
        int month = date.getMonth().getValue();
        int start = 0;
        //第一季度
        if (month >= 2 && month <= 4) {
            start = 2;
            //第二季度
        } else if (month >= 5 && month <= 7) {
            start = 5;
            //第三季度
        } else if (month >= 8 && month <= 10) {
            start = 8;
            //第四季度
        } else if ((month >= 11 && month <= 12)) {
            start = 11;
            //第四季度
        } else if (month == 1) {
            start = 11;
            month = 13;
        }
        return date.plusMonths(start - month).with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     * 获取某年的开始日期
     *
     * @param offset 0今年,1明年,-1去年,依次类推
     * @return
     */
    public static LocalDate yearStart(int offset) {
        return LocalDate.now().plusYears(offset).with(TemporalAdjusters.firstDayOfYear());
    }

    /**
     * 获取某月的字符形式(202005,202006,类似)
     *
     * @param offset 0当月,1下月,-1上月,依次类推
     * @return
     */
    public static String getMonthString(int offset) {
        final LocalDate localDate = LocalDate.now().plusMonths(offset);
        final String StringMonth = localDate.getMonthValue() < 10 ? "0" + localDate.getMonthValue() : "" + localDate.getMonthValue();
        return localDate.getYear() + StringMonth;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("当前时间是否为当月第一天:" + isFirstDayWithMonth());
        System.out.println("当前时间是否为本周第selectDay天:" + isSelectDayWithWeek(1));
        System.out.println("当前时间前minusDays天的时间是否跟当前时间同一个月份:" + isEqualsSameMonthWithMinusDays(21));
        getLocalDateTimeList4Hours(23);
        getLocalDateList4Days(30);
        System.out.println("间隔天数:" + until(LocalDate.of(2020, 4, 23)));
        System.out.println("某周开始日期:" + weekStart(-1).toString());
        System.out.println("某周结束日期:" + weekEnd(-1).toString());
        System.out.println("某月字符串:" + getMonthString(-1));
        System.out.println("间隔分钟:" + untilM(LocalDateTime.of(2022, 11, 19, 10, 38, 30)));


    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值