欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA8 LocalDateTime 的工具类

程序员文章站 2024-03-06 21:08:14
...

java8新推出的时间工具有很多优点,因此在此基础上进行了一定封装,方便了以后的一些开发

import com.qunji.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.stream.Stream;

类的具体内容

/**
 * 日期工具类
 *
 * @author jin.guo
 */
@Slf4j
public class DateTimeUtils {

    private DateTimeUtils() {
    }

    /**
     * 要用到的DATE Format的定义
     */
    public final static String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd"; // 年/月/日
    public final static String DATE_FORMAT_YYYY_MM_DD_CH = "yyyy年MM月dd日"; // 年/月/日
    public final static String DATE_FORMAT_DATE_XG_TIME = "yyyy/MM/dd HH:mm:ss"; // 年/月/日
    public final static String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; // 年/月/日
    public final static String DATE_FORMAT_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; // 年/月/日
    public final static String DATE_FORMAT_YYYYMMDD = "yyyyMMdd"; // 年/月/日
    public final static String DATE_FORMAT_YYYYMM = "yyyyMM"; // 年/月
    public final static String DATE_FORMAT_YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; // 年/月/日
    public final static String DATE_FORMAT_TIMEONLY_STRING = "HHmmss"; // 时/分/秒
    public final static String DATE_FORMAT_YYYYMMDDHHMMSSSSS = "yyyyMMddhhmmssSSS"; // 年/月/日
    public final static String DATE_FORMAT_DATESTR = "yyyy/MM/dd"; // 年/月/日
    public final static String DATE_FORMAT_MM_DD = "MM-dd"; // /月/日
    public final static String PERMANENT_DATE = "20991231"; //长久有效

    /**
     * 用到的FORMATTER
     */
    public final static DateTimeFormatter FORMATTER_YYYY_MM_DD_HH_MM_SS = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
    public final static DateTimeFormatter FORMATTER_YYYY_MM_DD = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYY_MM_DD);
    public final static DateTimeFormatter FORMATTER_YYYYMMDD = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYYMMDD);
    public final static DateTimeFormatter FORMATTER_YYYYMMDDHHMMSS = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYYMMDDHHMMSS);
    public final static DateTimeFormatter FORMATTER_DATESTR = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_DATESTR);
    public final static DateTimeFormatter FORMATTER_DATE_XG_TIME = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_DATE_XG_TIME);
    public final static DateTimeFormatter FORMATTER_HHMMSS = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_TIMEONLY_STRING);
    public final static DateTimeFormatter FORMATTER_YYYYMM = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYYMM);
    public final static DateTimeFormatter FORMATTER_YYYYMMDDHHMMSSSSS = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYYMMDDHHMMSSSSS);
    public final static DateTimeFormatter FORMATTER_YYYY_MM_DD_CH = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYY_MM_DD_CH);
    public final static DateTimeFormatter FORMATTER_YYYY_MM_DD_HH_MM = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM);
    public final static DateTimeFormatter FORMATTER_MM_DD = DateTimeFormatter.ofPattern(DateTimeUtils.DATE_FORMAT_MM_DD);

    /**
     * Date转LocalDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime date2localDateTime(Date date) {
        return Optional.of(date)
                .map(Date::toInstant)
                .map(instant -> instant.atZone(ZoneId.systemDefault()))
                .map(ZonedDateTime::toLocalDateTime)
                .orElse(null);
    }


    /**
     * LocalDateTime转Date
     *
     * @param localDateTime
     * @return
     */
    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        AtomicReference<Date> dateAtomicReference = new AtomicReference<>();
        Optional.ofNullable(localDateTime)
                .map(time -> time.atZone(ZoneId.systemDefault()))
                .map(ZonedDateTime::toInstant)
                .ifPresent(instant -> dateAtomicReference.set(Date.from(instant)));
        return dateAtomicReference.get();
    }

    /**
     * LocalDate转LocalDateTime
     *
     * @param localDate
     * @return
     */
    public static LocalDateTime localDate2LocalDateTime(LocalDate localDate) {
        return Optional.ofNullable(localDate).map(LocalDate::atStartOfDay).orElse(null);
    }

    /**
     * LocalDateTime转LocalDate
     *
     * @param localDateTime
     * @return
     */
    public static LocalDate localTimeDate2LocalDate(LocalDateTime localDateTime) {
        return Optional.ofNullable(localDateTime).map(LocalDateTime::toLocalDate).orElse(null);
    }

    /**
     * LocalDateTime转LocalTime
     *
     * @param localDateTime
     * @return
     */
    public static LocalTime localTimeDate2LocalTime(LocalDateTime localDateTime) {
        return Optional.ofNullable(localDateTime).map(LocalDateTime::toLocalTime).orElse(null);
    }

    /**
     * LocalTime转LocalDateTime
     *
     * @param localTime
     * @return
     */
    public static LocalDateTime localTime2LocalDateTime(LocalTime localTime) {
        return Optional.ofNullable(localTime).map(time -> LocalDateTime.of(LocalDate.of(0, 1, 1), time)).orElse(null);
    }

    /**
     * 通用转换字符串为时间
     *
     * @param str
     * @param parsePatterns
     * @return
     */
    public static LocalDateTime commonParseDateTime(String str, String parsePatterns) {
        return Optional.of(parsePatterns)
                .filter(StringUtils::isNotEmpty)
                .map(DateTimeFormatter::ofPattern)
                .map(dateTimeFormatter -> DateTimeUtils.commonParseDateTime(str, dateTimeFormatter))
                .orElse(null);
    }

    /**
     * 通用转换字符串为时间
     *
     * @param str
     * @param dateTimeFormatter
     * @return
     */
    public static LocalDateTime commonParseDateTime(String str, DateTimeFormatter dateTimeFormatter) {
        return Optional.of(str)
                .filter(StringUtils::isNotEmpty)
                .flatMap(source -> Optional.of(dateTimeFormatter)
                        .map(formatter -> formatter.parse(source))
                        .map(temporalAccessor -> {
                            boolean supportedDate = temporalAccessor.isSupported(ChronoField.DAY_OF_YEAR);
                            boolean supportedTime = temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY);
                            if (supportedDate && supportedTime) {
                                return LocalDateTime.from(temporalAccessor);
                            } else if (supportedDate) {
                                return DateTimeUtils.localDate2LocalDateTime(LocalDate.from(temporalAccessor));
                            } else if (supportedTime) {
                                return DateTimeUtils.localTime2LocalDateTime(LocalTime.from(temporalAccessor));
                            } else {
                                return null;
                            }
                        }))
                .orElse(null);
    }

    /**
     * 根据日期格式字符串解析日期字符串
     *
     * @param str
     * @param parsePatterns
     * @return
     */
    public static LocalDate parseDate(String str, String parsePatterns) {
        try {
            return Optional.of(parsePatterns)
                    .filter(StringUtils::isNotEmpty)
                    .map(DateTimeFormatter::ofPattern)
                    .map(dateTimeFormatter -> DateTimeUtils.parseDate(str, dateTimeFormatter))
                    .orElse(null);
        } catch (Exception e) {
            log.error("parseDate is error:::", e);
        }
        return null;
    }

    /**
     * 根据日期格式formatter解析日期字符串
     *
     * @param str
     * @param dateTimeFormatter
     * @return
     */
    public static LocalDate parseDate(String str, DateTimeFormatter dateTimeFormatter) {
        AtomicReference<LocalDate> localDate = new AtomicReference<>();
        try {
            Optional.of(dateTimeFormatter)
                    .map(timeFormatter -> LocalDate.parse(str, timeFormatter))
                    .ifPresent(localDate::set);
        } catch (Exception e) {
            log.error("parseDate is error:::", e);
        }
        return localDate.get();
    }

    /**
     * 根据时分秒格式字符串解析时分秒字符串
     *
     * @param str
     * @param parsePatterns
     * @return
     */
    public static LocalTime parseTime(String str, String parsePatterns) {
        try {
            return Optional.of(parsePatterns)
                    .filter(StringUtils::isNotEmpty)
                    .map(DateTimeFormatter::ofPattern)
                    .map(dateTimeFormatter -> DateTimeUtils.parseTime(str, dateTimeFormatter))
                    .orElse(null);
        } catch (Exception e) {
            log.error("parseTime is error:::", e);
        }
        return null;
    }

    /**
     * 根据时分秒格式formatter解析时分秒字符串
     *
     * @param str
     * @param dateTimeFormatter
     * @return
     */
    public static LocalTime parseTime(String str, DateTimeFormatter dateTimeFormatter) {
        AtomicReference<LocalTime> localTime = new AtomicReference<>();
        try {
            Optional.of(dateTimeFormatter)
                    .map(timeFormatter -> LocalTime.parse(str, timeFormatter))
                    .ifPresent(localTime::set);
        } catch (Exception e) {
            log.error("parseTime is error:::", e);
        }
        return localTime.get();
    }

    /**
     * 根据时间格式字符串解析时间字符串
     *
     * @param str           日期字符串
     * @param parsePatterns 日期格式字符串
     * @return 解析后LocalDateTime
     * @throws Exception
     */
    public static LocalDateTime parseDateTime(String str, String parsePatterns) {
        try {
            return Optional.of(parsePatterns)
                    .filter(StringUtils::isNotEmpty)
                    .map(DateTimeFormatter::ofPattern)
                    .map(dateTimeFormatter -> DateTimeUtils.parseDateTime(str, dateTimeFormatter))
                    .orElse(null);
        } catch (Exception e) {
            log.error("parseDateTime is error:::", e);
        }
        return null;
    }

    /**
     * 根据时间格式Formatter解析时间字符串
     *
     * @param str               日期字符串
     * @param dateTimeFormatter 日期格式Formatter
     * @return 解析后LocalDateTime
     * @throws Exception
     */
    public static LocalDateTime parseDateTime(String str, DateTimeFormatter dateTimeFormatter) {
        AtomicReference<LocalDateTime> localDateTime = new AtomicReference<>();
        try {
            Optional.of(dateTimeFormatter)
                    .map(timeFormatter -> LocalDateTime.parse(str, timeFormatter))
                    .ifPresent(localDateTime::set);
        } catch (Exception e) {
            log.error("parseDateTime is error:::", e);
        }
        return localDateTime.get();
    }


    /**
     * 判断输入日期是一个星期中的第几天(星期天为一个星期第一天)
     *
     * @param localDateTime
     * @return
     */
    public static Integer getWeekIndex(LocalDateTime localDateTime) {
        return Optional.of(localDateTime)
                .map(LocalDateTime::getDayOfWeek)
                .map(DayOfWeek::getValue)
                .orElse(null);

    }


    /**
     * 获取是星期几(一、二、三...)
     *
     * @param localDateTime
     * @return
     */
    public static String getWeekDay(LocalDateTime localDateTime) {
        Map<String, String> weekMap = new HashMap<>();
        weekMap.put("MONDAY", "一");
        weekMap.put("TUESDAY", "二");
        weekMap.put("WEDNESDAY", "三");
        weekMap.put("THURSDAY", "四");
        weekMap.put("FRIDAY", "五");
        weekMap.put("SATURDAY", "六");
        weekMap.put("SUNDAY", "日");
        return Optional.of(localDateTime)
                .map(LocalDateTime::getDayOfWeek)
                .map(dayOfWeek -> String.valueOf(localDateTime.getDayOfWeek()))
                .map(weekMap::get)
                .orElse(null);
    }


    /**
     * 取得指定日期格式的字符串
     *
     * @param localDate
     * @return String
     */
    public static String formatDate(LocalDate localDate, String format) {
        return Optional.of(localDate)
                .map(DateTimeUtils::localDate2LocalDateTime)
                .map(date2 -> formatDateTime(date2, format))
                .orElse("");
    }

    /**
     * 取得指定日期formatter格式的字符串
     *
     * @param localDate
     * @param dateTimeFormatter
     * @return
     */
    public static String formatDate(LocalDate localDate, DateTimeFormatter dateTimeFormatter) {
        return Optional.of(localDate)
                .map(DateTimeUtils::localDate2LocalDateTime)
                .map(date2 -> formatDateTime(date2, dateTimeFormatter))
                .orElse("");
    }

    /**
     * 取得指定时分秒格式的字符串
     *
     * @param localTime
     * @return String
     */
    public static String formatTime(LocalTime localTime, String format) {
        return Optional.of(localTime)
                .map(DateTimeUtils::localTime2LocalDateTime)
                .map(date2 -> formatDateTime(date2, format))
                .orElse("");
    }

    /**
     * 取得指定时分秒formatter格式的字符串
     *
     * @param localTime
     * @param dateTimeFormatter
     * @return
     */
    public static String formatTime(LocalTime localTime, DateTimeFormatter dateTimeFormatter) {
        return Optional.of(localTime)
                .map(DateTimeUtils::localTime2LocalDateTime)
                .map(date2 -> formatDateTime(date2, dateTimeFormatter))
                .orElse("");
    }

    /**
     * 取得通用日期时间格式字符串
     *
     * @param localDateTime
     * @return String
     */
    public static String formatDateTime(LocalDateTime localDateTime) {
        return formatDateTime(localDateTime, FORMATTER_YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 取得指定时间格式的字符串
     *
     * @param localDateTime
     * @return String
     */
    public static String formatDateTime(LocalDateTime localDateTime, String format) {
        try {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
            return formatDateTime(localDateTime, dateTimeFormatter);
        } catch (Exception e) {
            log.error("formatDate is error:::" + e.getMessage());
        }
        return "";
    }

    /**
     * 取得指定时间formatter格式的字符串
     *
     * @param localDateTime
     * @param dateTimeFormatter
     * @return
     */
    public static String formatDateTime(LocalDateTime localDateTime, DateTimeFormatter dateTimeFormatter) {
        AtomicReference<String> timeStr = new AtomicReference<>("");
        try {
            Optional.of(dateTimeFormatter)
                    .map(timeFormatter -> timeFormatter.format(localDateTime))
                    .ifPresent(timeStr::set);
        } catch (Exception e) {
            log.error("formatDate is error:::" + e.getMessage());
        }
        return timeStr.get();
    }

    /**
     * 取得指定日期格式的字符串
     *
     * @param date
     * @return String
     */
    public static String formatDate(String date, String format) {
        if (StringUtils.isEmpty(format)) {
            return date;
        }
        if (format.length() == 10) {
            return Optional.of(date)
                    .map(date1 -> DateTimeUtils.parseDate(date1, DateTimeUtils.FORMATTER_YYYYMMDD))
                    .map(localDate -> DateTimeUtils.formatDate(localDate, format))
                    .map(formatDateStr -> StringUtils.defaultIfBlank(formatDateStr, date))
                    .orElse(date);
        } else if (format.length() == 8) {
            return Optional.of(date)
                    .map(date1 -> DateTimeUtils.parseTime(date1, DateTimeUtils.FORMATTER_HHMMSS))
                    .map(localDate -> DateTimeUtils.formatTime(localDate, format))
                    .map(formatDateStr -> StringUtils.defaultIfBlank(formatDateStr, date))
                    .orElse(date);
        } else if (format.length() == 7) {
            return Optional.of(date)
                    .map(date1 -> DateTimeUtils.parseDate(date1, DateTimeUtils.FORMATTER_YYYYMM))
                    .map(localDate -> DateTimeUtils.formatDate(localDate, format))
                    .map(formatDateStr -> StringUtils.defaultIfBlank(formatDateStr, date))
                    .orElse(date);
        }
        return Optional.of(date)
                .map(date1 -> DateTimeUtils.parseDate(date1, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                .map(localDate -> DateTimeUtils.formatDate(localDate, format))
                .map(formatDateStr -> StringUtils.defaultIfBlank(formatDateStr, date))
                .orElse(date);
    }

    /**
     * 取得指定时间格式的字符串 带时分秒
     *
     * @param date
     * @return String
     */
    public static String formatDateTime(String date, String format) {
        return Optional.of(format)
                .filter(StringUtils::isNotEmpty)
                .map(formatStr -> Optional.of(date)
                        .map(date1 -> DateTimeUtils.parseDateTime(date1, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                        .map(localDate -> DateTimeUtils.formatDateTime(localDate, formatStr))
                        .map(formatDateStr -> StringUtils.defaultIfBlank(formatDateStr, date))
                        .orElse(date))
                .orElse(date);
    }


    /**
     * 根据传入的数字,输出相比现在大days天的数据
     *
     * @param days
     * @return LocalDateTime
     */
    public static LocalDateTime addDay(LocalDateTime localDateTime, long days) {
        return Optional.of(localDateTime)
                .map(time -> time.plusDays(days))
                .orElse(null);
    }

    /**
     * 根据传入的数字,输出相比现在大days天的数据
     *
     * @param days
     * @return LocalDate
     */
    public static LocalDate addDay(LocalDate localDate, long days) {
        return Optional.of(localDate)
                .map(date -> date.plusDays(days))
                .orElse(null);
    }

    /**
     * @功能描述:日期加减日
     * @param:
     * @return:
     */
    public static String addDay(String dateStr, int day) {
        return Optional.of(dateStr)
                .map(str -> DateTimeUtils.parseDate(str, DateTimeUtils.FORMATTER_YYYYMMDD))
                .map(localDate -> DateTimeUtils.addDay(localDate, day))
                .map(date -> DateTimeUtils.formatDate(date, DateTimeUtils.FORMATTER_YYYYMMDD))
                .orElse("");
    }


    /**
     * 时间加减小时
     *
     * @param localDateTime
     * @param hours
     * @return
     */
    public static LocalDateTime addHour(LocalDateTime localDateTime, long hours) {
        return Optional.of(localDateTime)
                .map(localTime -> localTime.plusHours(hours))
                .orElse(null);
    }


    /**
     * 时间加减小时
     *
     * @param dateTimeStr
     * @param hour
     * @return
     */
    public static String addHour(String dateTimeStr, long hour) {
        return Optional.of(dateTimeStr)
                .map(str -> DateTimeUtils.parseDateTime(dateTimeStr, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                .map(localDateTime -> DateTimeUtils.addHour(localDateTime, hour))
                .map(dateTime -> DateTimeUtils.formatDateTime(dateTime, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                .orElse("");
    }

    /**
     * 日期加减月
     *
     * @param localDateTime
     * @param month
     * @return
     */
    public static LocalDateTime addMonth(LocalDateTime localDateTime, long month) {
        return Optional.of(localDateTime)
                .map(localTime -> localTime.plusMonths(month))
                .orElse(null);
    }

    /**
     * 日期加减月
     *
     * @param localDate
     * @param month
     * @return
     */
    public static LocalDate addMonth(LocalDate localDate, long month) {
        return Optional.of(localDate)
                .map(date -> date.plusMonths(month))
                .orElse(null);
    }

    /**
     * @功能描述:日期加减月
     * @param:
     * @return:
     */
    public static String addMonth(String dateStr, long month) {
        if (StringUtils.isNotEmpty(dateStr)) {
            if (dateStr.length() == 14) {
                return Optional.of(dateStr)
                        .map(str -> DateTimeUtils.parseDateTime(str, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                        .map(localDateTime -> DateTimeUtils.addMonth(localDateTime, month))
                        .map(time -> DateTimeUtils.formatDateTime(time, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                        .orElse("");
            } else {
                return Optional.of(dateStr)
                        .map(str -> DateTimeUtils.parseDate(str, DateTimeUtils.FORMATTER_YYYYMMDD))
                        .map(localDate -> DateTimeUtils.addMonth(localDate, month))
                        .map(date -> DateTimeUtils.formatDate(date, DateTimeUtils.FORMATTER_YYYYMMDD))
                        .orElse("");
            }
        }
        return "";
    }

    /**
     * 日期加减年
     *
     * @param localDateTime
     * @param year
     * @return
     */
    public static LocalDateTime addYear(LocalDateTime localDateTime, long year) {
        return Optional.of(localDateTime)
                .map(time -> time.plusYears(year))
                .orElse(null);
    }

    /**
     * 日期加减年
     *
     * @param localDate
     * @param year
     * @return
     */
    public static LocalDate addYear(LocalDate localDate, long year) {
        return Optional.of(localDate)
                .map(date -> date.plusYears(year))
                .orElse(null);
    }

    /**
     * 日期加减年
     *
     * @param dateStr
     * @param year
     * @return
     */
    public static String addYear(String dateStr, long year) {
        AtomicReference<String> yearStr = new AtomicReference<>("");
        Optional.of(dateStr)
                .filter(StringUtils::isNotEmpty)
                .ifPresent(dateString -> {
                    if (dateString.length() == 14) {
                        yearStr.set(Optional.of(dateString)
                                .map(str -> DateTimeUtils.parseDateTime(str, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                                .map(localDateTime -> DateTimeUtils.addYear(localDateTime, year))
                                .map(localDateTime -> DateTimeUtils.formatDateTime(localDateTime, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                                .orElse(""));
                    } else {
                        yearStr.set(Optional.of(dateString)
                                .map(str -> DateTimeUtils.parseDate(str, DateTimeUtils.FORMATTER_YYYYMMDD))
                                .map(localDate -> DateTimeUtils.addYear(localDate, year))
                                .map(localDate -> DateTimeUtils.formatDate(localDate, DateTimeUtils.FORMATTER_YYYYMMDD))
                                .orElse(""));
                    }
                });
        return yearStr.get();
    }


    /**
     * 获取今天剩余的毫秒数 每天总共有86400000毫秒, 为了防止redis数据穿透,则预留1分钟强制走数据库
     *
     * @return 今天剩余的毫秒数
     */
    public static Long getMilliSecondsLeftToday() {
        return Optional.of(DateTimeUtils.addDay(LocalDateTime.now(), 1))
                .map(DateTimeUtils::localTimeDate2LocalDate)
                .map(localDate -> LocalDateTime.of(localDate, LocalTime.MIDNIGHT))
                .map(midNight -> ChronoUnit.MILLIS.between(LocalDateTime.now(), midNight))
                .orElse(null);
    }

    /**
     * 获取当前时间,对应数据的 AcceptTime 字段
     *
     * @return
     */
    public static String getAcceptTime() {
        return DateTimeUtils.formatDateTime(LocalDateTime.now(), DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
    }

    /**
     * 时间比较
     *
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static boolean compareDate(String startDateStr, String endDateStr) {
        AtomicReference<Boolean> compareFlag = new AtomicReference<>(false);
        try {
            DateTimeUtils.compareDateInit(startDateStr, endDateStr,
                    (startDate, optionalEndDate) -> optionalEndDate.ifPresent(endDate -> {
                        if (startDate.isAfter(endDate)) {
                            compareFlag.set(true);
                        }
                    }));
        } catch (Exception e) {
            log.error("compareTime is error:::" + e.getMessage());
        }
        return compareFlag.get();
    }

    private static void compareDateInit(String startDateStr, String endDateStr, BiConsumer<LocalDate, Optional<LocalDate>> action) {
        LocalDate startDate = Optional.of(DateTimeUtils.parseDate(startDateStr, DateTimeUtils.FORMATTER_YYYYMMDD)).orElse(LocalDate.now());
        Optional<LocalDate> optionalEndDate = Optional.of(DateTimeUtils.parseDate(endDateStr, DateTimeUtils.FORMATTER_YYYYMMDD));
        action.accept(startDate, optionalEndDate);
    }


    /**
     * 时间比较
     *
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static boolean compareDateMoreOrEqual(String startDateStr, String endDateStr) {
        AtomicReference<Boolean> compareFlag = new AtomicReference<>(false);
        try {
            DateTimeUtils.compareDateInit(startDateStr, endDateStr, (startDate, optionalEndDate) ->
                    optionalEndDate.ifPresent(endDate -> {
                        if (startDate.isAfter(endDate)
                                || startDate.isEqual(endDate)) {
                            compareFlag.set(true);
                        }
                    }));
        } catch (Exception e) {
            log.error("compareTimeMoreOrEqual is error:::" + e.getMessage());
        }
        return compareFlag.get();
    }


    private static void compareTimeInit(String startDateStr, String endDateStr, BiConsumer<LocalDateTime, Optional<LocalDateTime>> action) {
        LocalDateTime startTime = Optional.of(startDateStr)
                .map(start -> DateTimeUtils.parseDateTime(start, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                .orElse(LocalDateTime.now());
        Optional<LocalDateTime> optionalEndTime = Optional.of(endDateStr)
                .map(end -> DateTimeUtils.parseDateTime(end, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS));
        action.accept(startTime, optionalEndTime);
    }

    /**
     * 时间比较
     *
     * @param startTimeStr
     * @param endTimeStr
     * @return
     */
    public static boolean compareTime(String startTimeStr, String endTimeStr) {
        AtomicReference<Boolean> compareFlag = new AtomicReference<>(false);
        try {
            DateTimeUtils.compareTimeInit(startTimeStr, endTimeStr, (startTime, optionalEndTime) ->
                    optionalEndTime.ifPresent(endTime -> {
                        if (startTime.isAfter(endTime)) {
                            compareFlag.set(true);
                        }
                    }));
        } catch (Exception e) {
            log.error("compareTime1 is error:::" + e.getMessage());
        }
        return compareFlag.get();
    }

    /**
     * 时间比较
     *
     * @param startTimeStr
     * @param endTimeStr
     * @return
     */
    public static boolean compareTimeMoreOrEqual(String startTimeStr, String endTimeStr) {
        AtomicReference<Boolean> compareFlag = new AtomicReference<>(false);
        try {
            DateTimeUtils.compareTimeInit(startTimeStr, endTimeStr, (startTime, optionalEndTime) ->
                    optionalEndTime.ifPresent(endTime -> {
                        if (startTime.isAfter(endTime)
                                || startTime.isEqual(endTime)) {
                            compareFlag.set(true);
                        }
                    }));
        } catch (Exception e) {
            log.error("compareTime1 is error:::" + e.getMessage());
        }
        return compareFlag.get();
    }

    /**
     * String转化成对应的形式的翻译(yyyyMMdd -> yyyy-MM-dd)
     *
     * @param dateStr
     * @return
     */
    public static String changeDateStyle(String dateStr) {
        return Optional.of(dateStr)
                .filter(StringUtils::isNotEmpty)
                .map(date -> DateTimeUtils.parseDate(date, DateTimeUtils.FORMATTER_YYYYMMDD))
                .map(localDate -> DateTimeUtils.formatDate(localDate, DateTimeUtils.FORMATTER_YYYY_MM_DD))
                .map(date -> StringUtils.defaultIfBlank(date, dateStr))
                .orElse(dateStr);
    }

    /**
     * String转化成对应的形式的翻译(yyyyMMddHHmmss -> yyyy-MM-dd HH:mm:ss)
     *
     * @param time
     * @return
     */
    public static String changeTimeStyle(String time) {
        return Optional.of(time)
                .filter(StringUtils::isNotEmpty)
                .map(timeStr -> DateTimeUtils.parseDateTime(timeStr, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS))
                .map(localDateTime -> DateTimeUtils.formatDateTime(localDateTime, DateTimeUtils.FORMATTER_YYYY_MM_DD_HH_MM_SS))
                .map(str -> StringUtils.defaultIfBlank(str, time))
                .orElse(time);
    }

    /**
     * String转化成对应的形式的翻译
     *
     * @param pDate
     * @param pOrgStyle
     * @param pDateStyle
     * @return
     */
    public static String changeStyle(String pDate, String pOrgStyle, String pDateStyle) {
        return Optional.of(pDate)
                .filter(StringUtils::isNotEmpty)
                .map(pDateStr -> DateTimeUtils.parseDateTime(pDateStr, pOrgStyle))
                .map(localDateTime -> DateTimeUtils.formatDateTime(localDateTime, pDateStyle))
                .map(formatStr -> StringUtils.defaultIfBlank(formatStr, pDate))
                .orElse(pDate);
    }

    /**
     * 日期相减得到间隔
     *
     * @param dateMinuend
     * @param dateMeiosis
     * @param dateFormat
     * @return
     */
    public static long getMinusDay(String dateMinuend, String dateMeiosis, String dateFormat) throws Exception {
        long day = 0L;
        if (dateMinuend.length() != dateMeiosis.length() || dateMinuend.length() != dateFormat.length()) {
            log.error("dateMinuend【{}】;dateMeiosis【{}】;dateFormat【{}】", dateMinuend, dateMeiosis, dateFormat);
            throw new BusinessException("9999", "日期格式不正确");
        }
        try {
            day = Optional.of(dateMinuend)
                    .filter(StringUtils::isNotEmpty)
                    .map(dateMinuendStr -> DateTimeUtils.parseDateTime(dateMinuendStr, dateFormat))
                    .map(localDateTime1 -> Optional.of(dateMeiosis)
                            .filter(StringUtils::isNotEmpty)
                            .map(dateMeiosisStr -> DateTimeUtils.parseDateTime(dateMeiosisStr, dateFormat))
                            .map(localDateTime2 -> ChronoUnit.DAYS.between(localDateTime1, localDateTime2))
                            .orElseThrow(() -> new BusinessException("9999", "日期相减出错")))
                    .orElseThrow(() -> new BusinessException("9999", "日期相减出错"));
        } catch (BusinessException e) {
            log.error("dateMinuend【{}】;dateMeiosis【{}】;dateFormat【{}】", dateMinuend, dateMeiosis, dateFormat);
            throw e;
        } catch (Exception e) {
            log.error("dateMinuend【{}】;dateMeiosis【{}】;dateFormat【{}】", dateMinuend, dateMeiosis, dateFormat);
            throw new BusinessException("9999", "日期相减出错");
        }

        return day;
    }

    public static LocalDateTime[] getSeasonDate(LocalDateTime localDateTime) {
        return Optional.of(localDateTime)
                .map(time -> {
                    LocalDateTime[] season = new LocalDateTime[3];

                    int nSeason = getSeason(time);
                    if (nSeason == 1) {// 第一季度
                        season[0] = time.withMonth(Month.JANUARY.getValue());
                        season[1] = time.withMonth(Month.FEBRUARY.getValue());
                        season[2] = time.withMonth(Month.MARCH.getValue());
                    } else if (nSeason == 2) {// 第二季度
                        season[0] = time.withMonth(Month.APRIL.getValue());
                        season[1] = time.withMonth(Month.MAY.getValue());
                        season[2] = time.withMonth(Month.JUNE.getValue());
                    } else if (nSeason == 3) {// 第三季度
                        season[0] = time.withMonth(Month.JULY.getValue());
                        season[1] = time.withMonth(Month.AUGUST.getValue());
                        season[2] = time.withMonth(Month.SEPTEMBER.getValue());
                    } else if (nSeason == 4) {// 第四季度
                        season[0] = time.withMonth(Month.OCTOBER.getValue());
                        season[1] = time.withMonth(Month.NOVEMBER.getValue());
                        season[2] = time.withMonth(Month.DECEMBER.getValue());
                    }
                    return season;
                })
                .orElse(null);
    }

    public static int getSeason(LocalDateTime localDateTime) {
        int season = 0;

        Month month = localDateTime.getMonth();
        switch (month) {
            case JANUARY:
            case FEBRUARY:
            case MARCH:
                season = 1;
                break;
            case APRIL:
            case MAY:
            case JUNE:
                season = 2;
                break;
            case JULY:
            case AUGUST:
            case SEPTEMBER:
                season = 3;
                break;
            case OCTOBER:
            case NOVEMBER:
            case DECEMBER:
                season = 4;
                break;
            default:
                break;
        }
        return season;
    }

    /**
     * 取得季度第一天
     *
     * @param localDateTime
     * @return
     */
    public static LocalDateTime getFirstDateOfSeason(LocalDateTime localDateTime) {
        return Optional.of(localDateTime)
                .map(DateTimeUtils::getSeasonDate)
                .map(season -> getFirstDateOfMonth(season[0]))
                .orElse(null);
    }

    /**
     * 取得季度最后一天
     *
     * @param localDateTime
     * @return
     */
    public static LocalDateTime getLastDateOfSeason(LocalDateTime localDateTime) {
        return Optional.of(localDateTime)
                .map(DateTimeUtils::getSeasonDate)
                .map(season -> getLastDateOfMonth(season[2]))
                .orElse(null);
    }

    public static LocalDateTime getFirstDateOfMonth(LocalDateTime localDateTime) {
        return Optional.of(localDateTime).map(time -> time.with(TemporalAdjusters.firstDayOfMonth())).orElse(null);
    }


    /**
     * 取得月最后一天
     *
     * @param localDateTime
     * @return
     */
    public static LocalDateTime getLastDateOfMonth(LocalDateTime localDateTime) {
        return Optional.of(localDateTime).map(time -> time.with(TemporalAdjusters.lastDayOfMonth())).orElse(null);
    }

    /**
     * 后台翻译日期
     *
     * @param pDate
     * @param pDateStyle
     * @return String
     * @method:changeStyleDesc
     */
    public static String changeStyleDesc(String pDate, String pDateStyle) {
        return Optional.of(pDate)
                .filter(StringUtils::isNotEmpty)
                .map(pDateStr -> {
                    String pOrgStyle = DATE_FORMAT_YYYYMMDD;
                    if (pDateStr.length() == 14) {
                        pOrgStyle = DATE_FORMAT_YYYYMMDDHHMMSS;
                        return DateTimeUtils.parseDateTime(pDateStr, pOrgStyle);
                    } else {
                        return DateTimeUtils.localDate2LocalDateTime(DateTimeUtils.parseDate(pDateStr, pOrgStyle));
                    }
                })
                .map(time -> DateTimeUtils.formatDateTime(time, pDateStyle))
                .map(formatStr -> StringUtils.defaultIfBlank(formatStr, pDate))
                .orElse(pDate);
    }

    /**
     * 返回表示自定义格式的日期和时间的字符串
     */
    public static String getNowDate(String pDateStyle) {
        return DateTimeUtils.formatDateTime(LocalDateTime.now(), pDateStyle);
    }

    /**
     * 获取当前日期
     */
    public static String getCurrentOsDate() {
        return DateTimeUtils.formatDate(LocalDate.now(), DateTimeUtils.FORMATTER_YYYYMMDD);
    }

    /**
     * 获取当前时间,对应数据的 AcceptTime 字段
     *
     * @return
     */
    public static String getCurrentOsTime() {
        return DateTimeUtils.formatDateTime(LocalDateTime.now(), DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
    }

    /**
     * 获取当前时间毫秒
     *
     * @return
     */
    public static String getCurrentMillisecond() {
        return DateTimeUtils.formatDateTime(LocalDateTime.now(), DateTimeUtils.FORMATTER_YYYYMMDDHHMMSSSSS);
    }

    /**
     * 获取今天剩余的秒数
     *
     * @return 今天剩余的秒数
     */
    public static long getSecondsLeftToday() {
        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        return ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
    }


    /**
     * 获取当前年份yyyy
     * @param sourceDate
     * @return
     */
    public static String getYear(String sourceDate) {
        return Optional.of(sourceDate)
                .filter(StringUtils::isNotEmpty)
                .map(sourceStr -> {
                    if (sourceStr.length() == 14) {
                        return DateTimeUtils.parseDateTime(sourceStr, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
                    } else {
                        return DateTimeUtils.localDate2LocalDateTime(DateTimeUtils.parseDate(sourceStr, DateTimeUtils.FORMATTER_YYYYMMDD));
                    }
                })
                .map(localDateTime -> Integer.toString(localDateTime.getYear()))
                .orElse("");
    }

    /**
     * 获取当前月份
     * @param sourceDate
     * @return
     */
    public static String getMonth(String sourceDate) {
        return Optional.of(sourceDate)
                .filter(StringUtils::isNotEmpty)
                .map(sourceStr -> {
                    if (sourceStr.length() == 14) {
                        return DateTimeUtils.parseDateTime(sourceStr, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
                    } else {
                        return DateTimeUtils.localDate2LocalDateTime(DateTimeUtils.parseDate(sourceStr, DateTimeUtils.FORMATTER_YYYYMMDD));
                    }
                })
                .map(localDateTime -> Integer.toString(localDateTime.getMonth().getValue()))
                .orElse("");
    }


    /**
     * 根据日期,返回其星期数,周一为1,周日为7
     *
     * @param localDateTime
     * @return
     */
    public static String getWeekDayStr(LocalDateTime localDateTime) {
        return Optional.of(localDateTime)
                .map(DateTimeUtils::getWeekIndex)
                .map(weekIndex -> Integer.toString(weekIndex))
                .orElse("");
    }

    /**
     * 根据日期,返回其星期数,周一为1,周日为7
     *
     * @param localDate
     * @return
     */
    public static String getWeekDayStr(LocalDate localDate) {
        return Optional.of(localDate)
                .map(DateTimeUtils::localDate2LocalDateTime)
                .map(DateTimeUtils::getWeekIndex)
                .map(weekIndex -> Integer.toString(weekIndex))
                .orElse("");
    }

    /**
     * 获取两个日期之间的所有日期
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getDateList(String startDate, String endDate) {
        return Optional.of(startDate)
                .filter(StringUtils::isNotEmpty)
                .map(startDateStr -> DateTimeUtils.parseDate(startDateStr, DateTimeUtils.FORMATTER_YYYYMMDD))
                .map(start -> Optional.of(endDate)
                        .filter(StringUtils::isNotEmpty)
                        .map(endDateStr -> DateTimeUtils.parseDate(endDateStr, DateTimeUtils.FORMATTER_YYYYMMDD))
                        .map(end -> Optional.of(ChronoUnit.DAYS.between(start, end))
                                .filter(between -> between > 0)
                                .map(between -> {
                                    List<String> days = new ArrayList<>();
                                    Stream.iterate(start, day -> day.plusDays(1)).limit(between + 1).forEach(date -> {
                                        String formatDate = DateTimeUtils.formatDate(date, DateTimeUtils.FORMATTER_YYYYMMDD);
                                        days.add(formatDate);
                                    });
                                    return days;
                                }).orElse(new ArrayList<>())
                        ).orElse(new ArrayList<>())
                ).orElse(new ArrayList<>());
    }

    /**
     * 日期相减得秒数
     */
    public static Long getLastedTime(String firstDate, String secondDate) {
        LocalDateTime first = DateTimeUtils.parseDateTime(firstDate, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
        LocalDateTime second = DateTimeUtils.parseDateTime(secondDate, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
        return ChronoUnit.SECONDS.between(first, second);
    }

    public static void main(String[] args) {
//        LocalDateTime localDateTime = LocalDateTime.now();
//        Date date = DateTimeUtils.localDateTime2Date(localDateTime);
//        System.out.println(date);
//        LocalDate localDate = DateTimeUtils.localTimeDate2LocalDate(localDateTime);
//        System.out.println(localDate);
//        String s = DateTimeUtils.formatDate(localDate, DateTimeUtils.FORMATTER_YYYYMMDDHHMMSS);
//        System.out.println(s);
//        String localDateTime1 = DateTimeUtils.formatDateTime(localDateTime, DateTimeUtils.FORMATTER_YYYYMMDD);
//        System.out.println(localDateTime1);
//        LocalDate localDate = DateTimeUtils.parseDate("20190919", DateTimeUtils.FORMATTER_YYYYMMDD);
//        System.out.println(localDate);


//        List<String> dateList = getDateList("20190919", "20191104");
//        System.out.println(dateList);
//        LocalDateTime localDateTime = localTime2LocalDateTime(LocalTime.now());
//        System.out.println(localDateTime);
    }
}