日期时间转换工具类

import org.apache.commons.lang3.StringUtils;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

/**
 * 日期时间工具类
 * @date 2018/08/22
 */
public class DateTimeUtils {

    public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static final String DATE_FORMATTER_CON = "yyyyMMdd";

    /**
     * Date转换为LocalDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime convertToLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param dateTime
     * @return
     */
    public static Date convertToDate(LocalDateTime dateTime) {
        return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    }


    /**
     * 返回本地当前日期
     *
     * @return
     */
    public static LocalDate getCurrentLocalDate() {
        return LocalDate.now();
    }

    /**
     * 返回本地当前时间
     *
     * @return
     */
    public static LocalTime getCurrentLocalTime() {
        return LocalTime.now();
    }

    /**
     * 返回本地当前日期时间
     *
     * @return
     */
    public static LocalDateTime getCurrentLocalDateTime() {
        return LocalDateTime.now();
    }

    /**
     * 返回本地当前日期的固定或自定义字符串
     *
     * @return
     */
    public static String getCurrentDateStr(String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            return LocalDate.now().format(DateTimeFormatter.ofPattern(pattern));
        }
        return LocalDate.now().format(DATE_FORMATTER);
    }

    /**
     * 返回本地当前时间的固定或自定义字符串
     *
     * @return
     */
    public static String getCurrentTimeStr(String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            return LocalTime.now().format(DateTimeFormatter.ofPattern(pattern));
        }
        return LocalTime.now().format(TIME_FORMATTER);
    }

    /**
     * 返回本地当前日期时间的固定或自定义字符串
     *
     * @return
     */
    public static String getCurrentDateTimeStr(String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            return LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));
        }
        return LocalDateTime.now().format(DATETIME_FORMATTER);
    }

    /**
     * 将本地日期字符串根据pattern解析出本地日期
     *
     * @param dateStr
     * @param pattern
     * @return
     */
    public static LocalDate parseLocalDate(String dateStr, String pattern) {
        return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 将本地时间字符串根据pattern解析出本地时间
     *
     * @param timeStr
     * @param pattern
     * @return
     */
    public static LocalTime parseLocalTime(String timeStr, String pattern) {
        return LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 将本地日期字符串根据pattern解析出本地日期
     *
     * @param dateTimeStr
     * @param pattern
     * @return
     */
    public static LocalDateTime parseLocalDateTime(String dateTimeStr, String pattern) {
        return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 将本地日期转化为固定或自定义格式的字符串
     *
     * @param date
     * @return
     */
    public static String formatLocalDate(LocalDate date, String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            return date.format(DateTimeFormatter.ofPattern(pattern));
        }
        return date.format(DATE_FORMATTER);
    }

    /**
     * 将本地时间转化为固定或自定义格式的字符串
     *
     * @param time
     * @return
     */
    public static String formatLocalTime(LocalTime time, String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            return time.format(DateTimeFormatter.ofPattern(pattern));
        }
        return time.format(TIME_FORMATTER);
    }

    /**
     * 将本地日期时间转化为固定或自定义格式的字符串
     *
     * @param datetime
     * @return
     */
    public static String formatLocalDateTime(LocalDateTime datetime, String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            return datetime.format(DateTimeFormatter.ofPattern(pattern));
        }
        return datetime.format(DATETIME_FORMATTER);
    }

    /**
     * 获取指定日期的秒
     *
     * @param dateTime
     * @return
     */
    public static Long getSeconds(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
    }

    /**
     * 获取指定日期的毫秒(转时间戳)
     *
     * @param dateTime
     * @return
     */
    public static Long getMillis(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }


    /**
     * 时间戳转LocalDateTime
     *
     * @param timestamp
     * @return
     */
    public static LocalDateTime timestampToLDT(Long timestamp) {
        return LocalDateTime.ofEpochSecond(timestamp / 1000, (int) (timestamp % 1000) * 1000000, ZoneOffset.ofHours(8));
    }

    /**
     * 本地日期时间加上一个数
     *
     * @param dateTime
     * @param num
     * @param field    ChronoUnit.*(年、月、周、日、分...)
     * @return
     */
    public static LocalDateTime plus(LocalDateTime dateTime, long num, TemporalUnit field) {
        return dateTime.plus(num, field);
    }

    /**
     * 本地日期时间减去一个数
     *
     * @param dateTime
     * @param num
     * @param field    ChronoUnit.*(年、月、周、日、分...)
     * @return
     */
    public static LocalDateTime minu(LocalDateTime dateTime, long num, TemporalUnit field) {
        return dateTime.minus(num, field);
    }

    /**
     *本地日期时间减去一个数  Date时间格式
     * @param dateTime
     * @param num
     * @param field ChronoUnit.*(年、月、周、日、分...)
     * @return
     */
    public static Date getMinu(Date dateTime, long num, TemporalUnit field) {
        LocalDateTime localDateTime = DateTimeUtils.minu(DateTimeUtils.convertToLocalDateTime(dateTime),
                num, field);
        return DateTimeUtils.convertToDate(localDateTime);
    }
    /**
     *本地日期时间加一个数  Date时间格式
     * @param dateTime
     * @param num
     * @param field ChronoUnit.*(年、月、周、日、分...)
     * @return
     */
    public static Date getPlus(Date dateTime, long num, TemporalUnit field) {
        LocalDateTime localDateTime = DateTimeUtils.plus(DateTimeUtils.convertToLocalDateTime(dateTime),
                num, field);
        return DateTimeUtils.convertToDate(localDateTime);
    }
    /**
     * 获取本地两个日期的时间差
     *
     * @param startTime
     * @param endTime
     * @param field
     * @return
     */
    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, TemporalUnit field) {
        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
        if (field == ChronoUnit.YEARS) {
            return period.getYears();
        } else if (field == ChronoUnit.MONTHS) {
            return period.getYears() * 12 + period.getMonths();
        }
        return field.between(startTime, endTime);
    }

    /**
     * 根据LocalDateTime获取一天的开始时间
     *
     * @param dateTime
     * @return
     */
    public static LocalDateTime getDateStart(LocalDateTime dateTime) {
        return dateTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
    }

    /**
     * 根据LocalDateTime获取一天的结束时间
     *
     * @param dateTime
     * @return
     */
    public static LocalDateTime getDateEnd(LocalDateTime dateTime) {
        return dateTime.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
    }

    /**
     * 根据LocalDate获取一天的结束时间
     *
     * @param date
     * @return
     */
    public static LocalDateTime getLocalDateEnd(LocalDate date) {
        return date.atTime(23, 59, 59, 999999999);
    }

    /**
     * 根据LocalDate获取一天的开始时间
     *
     * @param date
     * @return
     */
    public static LocalDateTime getLocalDateStart(LocalDate date) {
        return date.atTime(0, 0, 0, 0);
    }

    /**
     * 是否当天
     *
     * @param dateTime
     * @return
     */
    public static boolean isToday(LocalDateTime dateTime) {
        return getCurrentLocalDate().equals(dateTime.toLocalDate());
    }

    public static void main(String[] args) {
        LocalDateTime current = LocalDateTime.now();
        System.out.println(isToday(current));
        // 输出结果 --> true
        System.out.println(current);
        // 输出结果 --> 2018-07-27T11:29:23.113
        System.out.println(getMillis(current));
        // 输出结果 --> 1532662163113
        System.out.println(plus(current, 6, ChronoUnit.DAYS));
        // 输出结果 --> 2018-08-02T11:29:23.113
        System.out.println(minu(current, 6, ChronoUnit.DAYS));
        // 输出结果 --> 2018-07-21T11:29:23.113
        System.out.println(minu(current, 29, ChronoUnit.DAYS));
        // 输出结果 --> 2018-06-28T11:29:23.113
        System.out.println(betweenTwoTime(LocalDateTime.of(2018, 7, 1, 0, 0, 0, 0),
                current, ChronoUnit.DAYS));
        // 输出结果 --> 26
        LocalDate todayDate = LocalDate.now();
        System.out.println(todayDate.minus(30, ChronoUnit.DAYS).toString());
        // 输出结果 --> 2018-06-27
        System.out.println(LocalDate.now().atTime(23, 59, 59));
        // 输出结果 --> 2018-07-27T23:59:59
        System.out.println(convertToDate(LocalDateTime.now()));
        // 输出结果 --> Fri Jul 27 11:29:23 CST 2018

        Long timestamp = getMillis(current);
        // 2018-07-30T11:28:32.054
        System.out.println(convertToDate(current).getTime());
        // 输出结果 --> 1532921312054
        System.out.println(timestamp);
        // 输出结果 --> 1532921312054
        System.out.println(timestampToLDT(timestamp));
        // 输出结果 --> 2018-07-30T11:28:32.054

        System.out.println(formatLocalDateTime(current, "yyyyMMddHHmmss"));
        // 输出结果 --> 20180731150923

        Long start = getMillis(current);
        Long end = getMillis(plus(getDateStart(current), 30, ChronoUnit.DAYS).
                plusHours(23).plusMinutes(59).plusSeconds(59));
        System.out.println(start);
        // 输出结果 --> 1534402914595
        System.out.println(end);
        // 输出结果 --> 1537027199000
        System.out.println(timestampToLDT(end));
        // 输出结果 --> 2018-09-15T23:59:59
    }
}

猜你喜欢

转载自blog.csdn.net/changhangshi/article/details/82117170