Java使用的时间转换类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateUtil {
    private static final Logger log = LoggerFactory.getLogger(BeanUtil.class);
    /**
     * 精确到微秒
     */
    public static final LocalTime MAX_OF_DAY_ACCURATE_TO_MICROSECONDS = LocalTime.of(23, 59, 59, 999_999_000);
    private static final String WEEK_PREFIX = "星期";
    private static final String SEVEN_ZH = "七";
    private static final String WEEK_SUN = "日";

    /**
     * yyyy-MM-dd 正则校验
     */
    private static final String YYYY_MM_DD_PATTERN = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|" +
            "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|" +
            "((0[48]|[2468][048]|[3579][26])00))-02-29)$";

    private DateUtil() {
    }

    /**
     * 解析指定格式化的日期字符串
     *
     * @param date   日期字符串
     * @param format 日期格式
     * @return Date 日期对象
     */
    public static Date parse(String date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            log.error("date error", e);
            throw new UtilRuntimeException("date.util.parse.date.error", "时间转化错误");
        }
    }

    /**
     * 解析指定格式化的日期字符串
     *
     * @param date 日期字符串
     * @return Date 日期对象
     */
    public static String parseToString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 获取当前时间的字符串
     *
     * @param format 日期格式
     * @return String Date 日期对象
     */
    public static String getCurrentDate(String format) {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
    }

    /**
     * 转换毫秒到指定格式时间字符串
     *
     * @param time   毫秒
     * @param format 格式
     * @return String
     */
    public static String convertLongTime(Long time, String format) {
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.ofHours(8));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return dateTimeFormatter.format(localDateTime);
    }

    /**
     * 将long时间转为指定格式时间字符串
     *
     * @param time     Long类型时间
     * @param format   格式
     * @param timeUnit 时间单位
     * @return
     */
    public static String convertLongTime(Long time, String format, TimeUnit timeUnit) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timeUnit.toMillis(time)), ZoneId.systemDefault());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return dateTimeFormatter.format(localDateTime);
    }


    /**
     * LocalDateTime转long
     *
     * @param localDateTime 时间
     * @return long 毫秒
     */
    public static long localTimeToLong(LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * long转LocalDateTime
     *
     * @param timeLong 毫秒
     * @return LocalDateTime 时间
     */
    public static LocalDateTime longToLocalTime(Long timeLong) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timeLong), ZoneId.systemDefault());
    }

    /**
     * LocalDateTime转String
     *
     * @param localDateTime 时间
     * @param pattern       格式
     * @return String
     */
    public static String localTimeToString(LocalDateTime localDateTime, String pattern) {
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }


    /**
     * String转LocalDateTime
     *
     * @param timeString 字符串时间
     * @param pattern    格式
     * @return LocalDateTime
     */
    public static LocalDateTime stringToLocalTime(String timeString, String pattern) {
        return LocalDateTime.parse(timeString, DateTimeFormatter.ofPattern(pattern));
    }


    /**
     * LocalDateTime转Date
     *
     * @param localDateTime 时间
     * @return Date
     */
    public static Date localTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date转LocalDateTime
     *
     * @param date 时间
     * @return LocalDateTime 时间
     */
    public static LocalDateTime dateToLocalTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * Date转LocalDateTime
     *
     * @param date 时间
     * @return LocalDateTime 时间
     */
    public static LocalDate dateToLocalDate(Date date) {
        if (Objects.isNull(date)) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * Date转LocalDateTime
     *
     * @param localDate 时间
     * @return LocalDate 时间
     */
    public static Date localDateToDate(LocalDate localDate) {
        if (Objects.isNull(localDate)) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    /**
     * 一天开始
     *
     * @return LocalDateTime
     */
    public static LocalDateTime startOfDay() {
        return startOfDay(LocalDate.now());
    }

    public static LocalDateTime startOfDay(LocalDate localDate) {
        return LocalDateTime.of(localDate, LocalTime.MIN);
    }

    public static LocalDateTime startOfDay(String timeString, String pattern) {
        LocalDate localDate = LocalDate.parse(timeString, DateTimeFormatter.ofPattern(pattern));
        return startOfDay(localDate);
    }

    public static LocalDateTime startOfDay(String timeString) {
        return startOfDay(timeString, Constant.DateFormat.YYYYMMDD);
    }

    /**
     * 一天最后一刻 精确到纳秒
     *
     * @return LocalDateTime
     */
    public static LocalDateTime endOfDay() {
        return endOfDay(LocalDate.now());
    }


    /**
     * 指定日期最后一刻 精确到纳秒
     *
     * @param localDate 指定日期
     * @return LocalDateTime
     */
    public static LocalDateTime endOfDay(LocalDate localDate) {
        return LocalDateTime.of(localDate, LocalTime.MAX);
    }

    /**
     * 指定日期最后一刻 精确到纳秒
     *
     * @param timeString 日期字符串
     * @param pattern    日期字符串的格式
     * @return 时间类型
     */
    public static LocalDateTime endOfDay(String timeString, String pattern) {
        LocalDate localDate = LocalDate.parse(timeString, DateTimeFormatter.ofPattern(pattern));
        return endOfDay(localDate);
    }

    /**
     * 指定日期最后一刻 精确到纳秒
     *
     * @param timeString 日期字符串,格式为yyyy-MM-dd
     * @return 时间类型
     */
    public static LocalDateTime endOfDay(String timeString) {
        return endOfDay(timeString, Constant.DateFormat.YYYYMMDD);
    }

    /**
     * 一天最后一刻  精确到微秒
     *
     * @param localDate 时间
     * @return 时间
     */
    public static LocalDateTime endOfDayForMicroseconds(LocalDate localDate) {
        return LocalDateTime.of(localDate, MAX_OF_DAY_ACCURATE_TO_MICROSECONDS);
    }

    /**
     * 指定日期最后一刻 精确到微秒
     *
     * @param timeString 日期字符串,格式为yyyy-MM-dd
     * @return 时间
     */
    public static LocalDateTime endOfDayForMicroseconds(String timeString) {
        return endOfDayForMicroseconds(timeString, Constant.DateFormat.YYYYMMDD);
    }

    /**
     * 指定日期最后一刻 精确到微秒
     *
     * @param timeString 日期字符串
     * @param pattern    日期字符串的格式
     * @return 时间
     */
    public static LocalDateTime endOfDayForMicroseconds(String timeString, String pattern) {
        LocalDate localDate = LocalDate.parse(timeString, DateTimeFormatter.ofPattern(pattern));
        return endOfDayForMicroseconds(localDate);
    }

    /**
     * 获取指定日期的周一的开始日期时间
     *
     * @param localDateTime
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getBeginOfWeek(LocalDateTime localDateTime) {
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
        int i = dayOfWeek.get(ChronoField.DAY_OF_WEEK);
        LocalDateTime begin = localDateTime.plusDays(-1 * i + 1);
        return LocalDateTime.of(LocalDate.from(begin), LocalTime.MIN);
    }

    /**
     * 获取指定日期的周日的结束日期时间
     *
     * @param localDateTime
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getEndOfWeek(LocalDateTime localDateTime) {
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
        int i = dayOfWeek.get(ChronoField.DAY_OF_WEEK);
        LocalDateTime end = localDateTime.plusDays(7 - i);
        return LocalDateTime.of(LocalDate.from(end), LocalTime.MAX);
    }

    /**
     * 获取指定日期的月初的开始日期时间
     *
     * @param localDateTime
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getBeginOfMonth(LocalDateTime localDateTime) {
        LocalDateTime begin = localDateTime.with(TemporalAdjusters.firstDayOfMonth());
        return LocalDateTime.of(LocalDate.from(begin), LocalTime.MIN);
    }

    /**
     * 获取指定日期的月末的结束日期时间
     *
     * @param localDateTime
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getEndOfMonth(LocalDateTime localDateTime) {
        LocalDateTime end = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
        return LocalDateTime.of(LocalDate.from(end), LocalTime.MAX);
    }

    /**
     * 获取指定日期的年初的开始日期时间
     *
     * @param localDateTime
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getBeginOfYear(LocalDateTime localDateTime) {
        LocalDateTime begin = localDateTime.with(TemporalAdjusters.firstDayOfYear());
        return LocalDateTime.of(LocalDate.from(begin), LocalTime.MIN);
    }

    /**
     * 获取指定日期的年末的结束日期时间
     *
     * @param localDateTime
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getEndOfYear(LocalDateTime localDateTime) {
        LocalDateTime end = localDateTime.with(TemporalAdjusters.lastDayOfYear());
        return LocalDateTime.of(LocalDate.from(end), LocalTime.MAX);
    }

    /**
     * 比较第一个日期是否小于第二个日期
     *
     * @param firstDate  第一个日期
     * @param secondDate 第二个日期
     * @return boolean true-小于;false-大于
     */
    public static boolean localDateIsBefore(LocalDate firstDate, LocalDate secondDate) {
        return firstDate.isBefore(secondDate);
    }


    /**
     * 比较第一个日期是否大于第二个日期
     *
     * @param firstDate  第一个日期
     * @param secondDate 第二个日期
     * @return boolean true-大于;false-不大于
     */
    public static boolean localDateIsAfter(LocalDate firstDate, LocalDate secondDate) {
        return firstDate.isAfter(secondDate);
    }

    /**
     * 比较两个日期是否相等
     *
     * @param firstDate  第一个日期
     * @param secondDate 第二个日期
     * @return boolean true-相等;false-不相等
     */
    public static boolean localDateIsEqual(LocalDate firstDate, LocalDate secondDate) {
        return firstDate.isEqual(secondDate);
    }

    /**
     * 计算俩个时间的差值
     *
     * @param one      减数
     * @param two      被减数
     * @param timeUnit 时间单位
     * @return long
     */
    public static long timeDifference(LocalDateTime one, LocalDateTime two, TimeUnit timeUnit) {
        long millisecondsDifference = localTimeToLong(one) - localTimeToLong(two);
        switch (timeUnit) {
            case DAYS:
                return TimeUnit.MILLISECONDS.toDays(millisecondsDifference);
            case HOURS:
                return TimeUnit.MILLISECONDS.toHours(millisecondsDifference);
            case MINUTES:
                return TimeUnit.MILLISECONDS.toMinutes(millisecondsDifference);
            case SECONDS:
                return TimeUnit.MILLISECONDS.toSeconds(millisecondsDifference);
            case MILLISECONDS:
                return TimeUnit.MILLISECONDS.toMillis(millisecondsDifference);
            default:
                return -1L;
        }
    }

    /**
     * 获取周几
     * 如:输入2020-08-09 12:02:02 输出 星期日
     *
     * @param timeString 时间字符
     * @param pattern    时间格式
     * @return 周几
     */
    public static String getWeekByLocalDateTime(String timeString, String pattern) {
        return getWeekByLocalDateTime(stringToLocalTime(timeString, pattern));
    }

    /**
     * 获取周几
     * 如:输入2020-08-09 12:02:02  输出 星期日
     *
     * @param localDateTime 时间
     * @return 周几
     */
    public static String getWeekByLocalDateTime(LocalDateTime localDateTime) {
        if (Objects.isNull(localDateTime)) {
            return Constant.Symbol.SPACE;
        }
        String weekOfDay = NumberUtil.convertNumberToZh(localDateTime.getDayOfWeek().getValue());
        if (SEVEN_ZH.equals(weekOfDay)) {
            weekOfDay = WEEK_SUN;
        }
        return WEEK_PREFIX + weekOfDay;
    }


    /**
     * string转LocalDate
     *
     * @param dateString 日期字符串yyyy-MM-dd
     * @return 日期
     */
    public static LocalDate stringToLocalDate(String dateString) {
        return stringToLocalDate(dateString, Constant.DateFormat.YYYYMMDD);
    }

    /**
     * 字符串转换为localDate
     *
     * @param dateString 时间字符串
     * @param pattern    日期格式
     * @return 日期
     */
    public static LocalDate stringToLocalDate(String dateString, String pattern) {
        if (!StringUtils.isEmpty(dateString)) {
            dateString = dateString.trim();
            DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .appendPattern(pattern)
                    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                    .toFormatter();
            return LocalDate.parse(dateString, dateTimeFormatter);
        }
        return null;
    }

    /**
     * 计算某月的第一天
     *
     * @param dateString 日期字符串
     * @param pattern    日期格式
     * @return 第一天日期
     */
    public static LocalDate startDayOfMonth(String dateString, String pattern) {
        if (!StringUtils.isEmpty(dateString)) {
            dateString = dateString.trim();
            LocalDate localDate = stringToLocalDate(dateString, pattern);
            return startDayOfMonth(localDate);
        }
        return null;
    }

    /**
     * 计算某月的第一天
     *
     * @param localDate 日期
     * @return 第一天日期
     */
    public static LocalDate startDayOfMonth(LocalDate localDate) {
        if (!Objects.isNull(localDate)) {
            LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
            return firstDayOfMonth;
        }
        return null;
    }

    /**
     * 计算某月的最后一天
     *
     * @param dateString 日期字符串
     * @param pattern    日期格式
     * @return 最后一天日期
     */
    public static LocalDate endDayOfMonth(String dateString, String pattern) {
        if (!StringUtils.isEmpty(dateString)) {
            dateString = dateString.trim();
            LocalDate localDate = stringToLocalDate(dateString, pattern);
            return endDayOfMonth(localDate);
        }
        return null;
    }

    /**
     * 计算某月的最后一天
     *
     * @param localDate 当前日期
     * @return 最后一天
     */
    public static LocalDate endDayOfMonth(LocalDate localDate) {
        if (!Objects.isNull(localDate)) {
            LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
            return lastDayOfMonth;
        }
        return null;
    }


    /**
     * 获取这个月的总天数
     *
     * @param date 日期
     * @return int 当月天数
     */
    public static int getDaysOfMonth(LocalDate date) {
        return date.getMonth().maxLength();
    }

    /**
     * 获取日期的月份进度
     *
     * @param date         日期
     * @param scala        保留位数
     * @param roundingMode 保留规则
     * @return java.math.BigDecimal 百分比
     */
    public static BigDecimal progressDayOfMonth(LocalDate date, int scala, RoundingMode roundingMode) {
        int dayOfDate = date.getDayOfMonth();
        int daysOfMonth = getDaysOfMonth(date);
        return BigDecimal.valueOf(dayOfDate).divide(BigDecimal.valueOf(daysOfMonth), scala, roundingMode);
    }

    /**
     * 获取前一天/月/周/年等
     *
     * @param date       日期
     * @param pattern    日期格式
     * @param chronoUnit 日期类型
     * @return
     */
    public static String getBeforeByChronoUnit(String date, String pattern, ChronoUnit chronoUnit) {
        LocalDate localDate = stringToLocalDate(date, pattern);
        localDate = localDate.plus(-1, chronoUnit);
        return localDateToString(localDate, pattern);
    }

    /**
     * localDate转字符串
     *
     * @param localDate 日期
     * @param pattern   日期格式
     * @return
     */
    public static String localDateToString(LocalDate localDate, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return localDate.format(dateTimeFormatter);
    }


    /**
     * localDate转字符串
     *
     * @param localDate 日期
     * @param pattern   日期格式
     * @return
     */
    public static String localDateTimeToString(LocalDateTime localDate, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return localDate.format(dateTimeFormatter);
    }

    /**
     * 获取前几天/月/周/年等
     *
     * @param date       日期
     * @param amount     加减时间单位个数
     * @param pattern    日期格式
     * @param chronoUnit 日期类型
     * @return
     */
    public static String plusByChronoUnit(String date, String pattern, int amount, ChronoUnit chronoUnit) {
        LocalDate localDate = stringToLocalDate(date, pattern);
        localDate = localDate.plus(amount, chronoUnit);
        return localDateToString(localDate, pattern);
    }

    /**
     * 校验日期格式 yyyy-DD-mm
     *
     * @param string
     */
    public static Boolean checkDate(String string) {

        Pattern p = Pattern.compile(YYYY_MM_DD_PATTERN);

        Matcher m = p.matcher(string);

        return m.matches();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DevanLove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值