java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java8日期时间工具类

Java8中常用的日期时间工具类总结

作者:qq_44438941

这篇文章主要为大家详细介绍了Java8中常用的三个日期时间工具类,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下

本文提供了3种日期时间工具类,大家可以任选一种使用

第一种

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String TIME_FORMAT = "HH:mm:ss";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    /**
     * 格式化日期
     * 
     * @param date
     * @return yyyy-MM-dd
     */
    public static String getFormatDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
        return format.format(date);
    }
    /**
     * 格式化时间
     * 
     * @param date
     * @return HH:mm:ss
     */
    public static String getFormatTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(TIME_FORMAT);
        return format.format(date);
    }
    /**
     * 格式化日期及时间
     * 
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getFormatDateTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
        return format.format(date);
    }
    /**
     * 格式化日期
     * 
     * @param localDate
     * @return
     */
    public static String getFormatDate(LocalDate localDate) {
        return localDate.format(DATE_FORMATTER);
    }
    /**
     * 格式化时间
     * 
     * @param localDate
     * @return
     */
    public static String getFormatTime(LocalDateTime localDateTime) {
        return localDateTime.format(TIME_FORMATTER);
    }
    /**
     * 格式化日期及时间
     * 
     * @param localDate
     * @return
     */
    public static String getFormatDateTime(LocalDateTime localDateTime) {
        return localDateTime.format(DATE_TIME_FORMATTER);
    }
    /**
     * 日期时间字符串转LocalDateTime
     * 
     * @param dateStr
     * @return
     */
    public static LocalDateTime dateStrToLocalDateTime(String dateStr) {
        return LocalDateTime.parse(dateStr, DATE_TIME_FORMATTER);
    }
    /**
     * 日期字符串转LocalDate
     * 
     * @param dateStr
     * @return
     */
    public static LocalDate dateStrToLocalDate(String dateStr) {
        return LocalDate.parse(dateStr, DATE_FORMATTER);
    }
    /**
     * 日期字符串 转 Date
     * 
     * @param dateStr
     * @return
     */
    public static Date dateStrToDate(String dateStr) {
        return Date.from(LocalDate.parse(dateStr, DATE_FORMATTER).atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
    /**
     * 日期时间字符串 转 Date
     * 
     * @param dateStr
     * @return
     */
    public static Date dateTimeStrToDate(String dateStr) {
        return Date.from(LocalDateTime.parse(dateStr, DATE_TIME_FORMATTER).atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * LocalDate 转 Date
     * 
     * @param localDate
     * @return
     */
    public static Date localDateToDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
    /**
     * LocalDateTime 转 Date
     * 
     * @param localDateTime
     * @return
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * Date 转 LocalDate
     * 
     * @return
     */
    public static LocalDate dateToLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
    /**
     * Date 转 LocalDateTime
     * 
     * @param date
     * @return
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
    /**
     * 计算两个日期时间差
     * 
     * @param start yyyy-MM-dd HH:mm:ss
     * @param end yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static long dateDifference(String start, String end) {
        SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
        try {
            Date startTime = format.parse(start);
            Date endTime = format.parse(end);
            return endTime.getTime() - startTime.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }
    /**
     * 计算两个日期之间的天数差
     * 
     * @param start 2018-03-01 12:00:00
     * @param end   2018-03-12 12:00:00
     * @return
     */
    public static long calculationDays(String start, String end) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date fromDate = simpleFormat.parse(start);
            Date toDate = simpleFormat.parse(end);
            long from = fromDate.getTime();
            long to = toDate.getTime();
            long days = (int) ((to - from) / (1000 * 60 * 60 * 24));
            return days;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }
    /**
     * 计算小时差
     * 
     * @param start
     * @param end
     * @return
     */
    public static long calculationHours(String start, String end) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date fromDate = simpleFormat.parse(start);
            Date toDate = simpleFormat.parse(end);
            long from = fromDate.getTime();
            long to = toDate.getTime();
            long hours = (int) ((to - from) / (1000 * 60 * 60));
            return hours;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }
    /**
     * 计算分钟差
     * 
     * @param start
     * @param end
     * @return
     */
    public static long calculationMinutes(String start, String end) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date fromDate = simpleFormat.parse(start);
            Date toDate = simpleFormat.parse(end);
            long from = fromDate.getTime();
            long to = toDate.getTime();
            long minutes = (int) ((to - from) / (1000 * 60));
            return minutes;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }
    /**
     * 计算两个日期之间的秒数差
     * @param start
     * @param end
     * @return
     */
    public static long calculationSecond(String start, String end) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date fromDate = simpleFormat.parse(start);
            Date toDate = simpleFormat.parse(end);
            long from = fromDate.getTime();
            long to = toDate.getTime();
            long seconds = (int) ((to - from) / 1000);
            return seconds;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }
    /**
     * 获取两个日期的差  field参数为ChronoUnit.*
     * @param startTime
     * @param endTime
     * @param field  单位(年月日时分秒)
     * @return
     */
    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
        if (field == ChronoUnit.YEARS) 
            return period.getYears();
        if (field == ChronoUnit.MONTHS) 
            return period.getYears() * 12 + period.getMonths();
        return field.between(startTime, endTime);
    }
    /**
     * 日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
     * @param time
     * @param number
     * @param field
     * @return
     */
    public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
        return time.plus(number, field);
    }
    /**
     * 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
     * @param time
     * @param number
     * @param field
     * @return
     */
    public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field){
        return time.minus(number,field);
    }
    /**
     * 根据field不同加减不同值
     * @param date  
     * @param field  Calendar.YEAR
     * @param number 1000/-1000
     */
    public static Date calculationDate(Date date, int field, int number) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(field, number);
        return calendar.getTime();
    }
    /**
     * 比较两个日期先后
     * @param date1
     * @param date2
     * @return
     */
    public static boolean compareDate(Date firstDate, Date secondDate) {
        return firstDate.getTime() < secondDate.getTime();
    }
    /**
     * 比较第一个日期是否大于第二个日期
     * @param firstDate 第一个日期
     * @param secondDate 第二个日期
     * @return true-大于;false-不大于
     */
    public boolean localDateIsBefore(LocalDate firstDate, LocalDate secondDate) {
        return firstDate.isBefore(secondDate);
    }
    public static void main(String[] args) {
        Date date = new Date();
        LocalDateTime localDate = DateUtils.dateToLocalDateTime(date);
        System.out.println(localDate);
        String start = "2020-03-01 12:00:00";
        String end = "2022-03-12 12:01:00";
        long seconds = DateUtils.calculationSecond(start, end);
        System.out.println("相差秒数: " + seconds);
        long minutes = DateUtils.calculationMinutes(start, end);
        System.out.println("相差分钟数: " + minutes);
        long days = DateUtils.calculationDays(start, end);
        System.out.println("相差天数: " + days);
        LocalDateTime startTime = LocalDateTime.of(2000, 10, 13, 11, 11);
        LocalDateTime endTime = LocalDateTime.of(2000, 10, 14, 13, 13);
        long time = DateUtils.betweenTwoTime(startTime, endTime, ChronoUnit.SECONDS);
        System.out.println(time);
        date = DateUtils.calculationDate(date, Calendar.DATE, -10);
        System.out.println("减去10天: " + DateUtils.getFormatDate(date));
    }
}

第二种

/**
 * Java8日期时间工具类
 *
 * @author 
 * @date 
 */
public class LocalDateUtils {
    /**
     * 显示年月日时分秒,例如 2015-08-11 09:51:53.
     */
    public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    /**
     * 仅显示年月日,例如 2015-08-11.
     */
    public static final String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 仅显示时分秒,例如 09:51:53.
     */
    public static final String TIME_PATTERN = "HH:mm:ss";
    /**
     * 显示年月日时分秒(无符号),例如 20150811095153.
     */
    public static final String UNSIGNED_DATETIME_PATTERN = "yyyyMMddHHmmss";
    /**
     * 仅显示年月日(无符号),例如 20150811.
     */
    public static final String UNSIGNED_DATE_PATTERN = "yyyyMMdd";
    /**
     * 春天;
     */
    public static final Integer SPRING = 1;
    /**
     * 夏天;
     */
    public static final Integer SUMMER = 2;
    /**
     * 秋天;
     */
    public static final Integer AUTUMN = 3;
    /**
     * 冬天;
     */
    public static final Integer WINTER = 4;
    /**
     * 星期日;
     */
    public static final String SUNDAY = "星期日";
    /**
     * 星期一;
     */
    public static final String MONDAY = "星期一";
    /**
     * 星期二;
     */
    public static final String TUESDAY = "星期二";
    /**
     * 星期三;
     */
    public static final String WEDNESDAY = "星期三";
    /**
     * 星期四;
     */
    public static final String THURSDAY = "星期四";
    /**
     * 星期五;
     */
    public static final String FRIDAY = "星期五";
    /**
     * 星期六;
     */
    public static final String SATURDAY = "星期六";
    /**
     * 年
     */
    private static final String YEAR = "year";
    /**
     * 月
     */
    private static final String MONTH = "month";
    /**
     * 周
     */
    private static final String WEEK = "week";
    /**
     * 日
     */
    private static final String DAY = "day";
    /**
     * 时
     */
    private static final String HOUR = "hour";
    /**
     * 分
     */
    private static final String MINUTE = "minute";
    /**
     * 秒
     */
    private static final String SECOND = "second";
    /**
     * 获取当前日期和时间字符串.
     *
     * @return String 日期时间字符串,例如 2015-08-11 09:51:53
     */
    public static String getLocalDateTimeStr() {
        return format(LocalDateTime.now(), DATETIME_PATTERN);
    }
    /**
     * 获取当前日期字符串.
     *
     * @return String 日期字符串,例如2015-08-11
     */
    public static String getLocalDateStr() {
        return format(LocalDate.now(), DATE_PATTERN);
    }
    /**
     * 获取当前时间字符串.
     *
     * @return String 时间字符串,例如 09:51:53
     */
    public static String getLocalTimeStr() {
        return format(LocalTime.now(), TIME_PATTERN);
    }
    /**
     * 获取当前星期字符串.
     *
     * @return String 当前星期字符串,例如 星期二
     */
    public static String getDayOfWeekStr() {
        return format(LocalDate.now(), "E");
    }
    /**
     * 获取指定日期是星期几
     *
     * @param localDate 日期
     * @return String 星期几
     */
    public static String getDayOfWeekStr(LocalDate localDate) {
        String[] weekOfDays = {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};
        int dayOfWeek = localDate.getDayOfWeek().getValue() - 1;
        return weekOfDays[dayOfWeek];
    }
    /**
     * 获取日期时间字符串
     *
     * @param temporal 需要转化的日期时间
     * @param pattern  时间格式
     * @return String 日期时间字符串,例如 2015-08-11 09:51:53
     */
    public static String format(TemporalAccessor temporal, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(temporal);
    }
    /**
     * 日期时间字符串转换为日期时间(java.time.LocalDateTime)
     *
     * @param localDateTimeStr 日期时间字符串
     * @param pattern          日期时间格式 例如DATETIME_PATTERN
     * @return LocalDateTime 日期时间
     */
    public static LocalDateTime parseLocalDateTime(String localDateTimeStr, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(localDateTimeStr, dateTimeFormatter);
    }
    /**
     * 日期字符串转换为日期(java.time.LocalDate)
     *
     * @param localDateStr 日期字符串
     * @param pattern      日期格式 例如DATE_PATTERN
     * @return LocalDate 日期
     */
    public static LocalDate parseLocalDate(String localDateStr, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDate.parse(localDateStr, dateTimeFormatter);
    }
    /**
     * 获取指定日期时间加上指定数量日期时间单位之后的日期时间.
     *
     * @param localDateTime 日期时间
     * @param num           数量
     * @param chronoUnit    日期时间单位
     * @return LocalDateTime 新的日期时间
     */
    public static LocalDateTime plus(LocalDateTime localDateTime, int num, ChronoUnit chronoUnit) {
        return localDateTime.plus(num, chronoUnit);
    }
    /**
     * 获取指定日期时间减去指定数量日期时间单位之后的日期时间.
     *
     * @param localDateTime 日期时间
     * @param num           数量
     * @param chronoUnit    日期时间单位
     * @return LocalDateTime 新的日期时间
     */
    public static LocalDateTime minus(LocalDateTime localDateTime, int num, ChronoUnit chronoUnit) {
        return localDateTime.minus(num, chronoUnit);
    }
    /**
     * 根据ChronoUnit计算两个日期时间之间相隔日期时间
     *
     * @param start      开始日期时间
     * @param end        结束日期时间
     * @param chronoUnit 日期时间单位
     * @return long 相隔日期时间
     */
    public static long getChronoUnitBetween(LocalDateTime start, LocalDateTime end, ChronoUnit chronoUnit) {
        return Math.abs(start.until(end, chronoUnit));
    }
    /**
     * 根据ChronoUnit计算两个日期之间相隔年数或月数或天数
     *
     * @param start      开始日期
     * @param end        结束日期
     * @param chronoUnit 日期时间单位,(ChronoUnit.YEARS,ChronoUnit.MONTHS,ChronoUnit.WEEKS,ChronoUnit.DAYS)
     * @return long 相隔年数或月数或天数
     */
    public static long getChronoUnitBetween(LocalDate start, LocalDate end, ChronoUnit chronoUnit) {
        return Math.abs(start.until(end, chronoUnit));
    }
    /**
     * 获取本年第一天的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfYearStr() {
        return getFirstDayOfYearStr(LocalDateTime.now());
    }
    /**
     * 获取本年最后一天的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfYearStr() {
        return getLastDayOfYearStr(LocalDateTime.now());
    }
    /**
     * 获取指定日期当年第一天的日期字符串
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfYearStr(LocalDateTime localDateTime) {
        return getFirstDayOfYearStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期当年最后一天的日期字符串
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfYearStr(LocalDateTime localDateTime) {
        return getLastDayOfYearStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期当年第一天的日期字符串,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfYearStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withDayOfYear(1).withHour(0).withMinute(0).withSecond(0), pattern);
    }
    /**
     * 获取指定日期当年最后一天的日期字符串,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfYearStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(TemporalAdjusters.lastDayOfYear()).withHour(23).withMinute(59).withSecond(59), pattern);
    }
    /**
     * 获取本月第一天的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfMonthStr() {
        return getFirstDayOfMonthStr(LocalDateTime.now());
    }
    /**
     * 获取本月最后一天的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfMonthStr() {
        return getLastDayOfMonthStr(LocalDateTime.now());
    }
    /**
     * 获取指定日期当月第一天的日期字符串
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getFirstDayOfMonthStr(LocalDateTime localDateTime) {
        return getFirstDayOfMonthStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期当月最后一天的日期字符串
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfMonthStr(LocalDateTime localDateTime) {
        return getLastDayOfMonthStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期当月第一天的日期字符串,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfMonthStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0), pattern);
    }
    /**
     * 获取指定日期当月最后一天的日期字符串,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfMonthStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59), pattern);
    }
    /**
     * 获取本周第一天的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfWeekStr() {
        return getFirstDayOfWeekStr(LocalDateTime.now());
    }
    /**
     * 获取本周最后一天的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfWeekStr() {
        return getLastDayOfWeekStr(LocalDateTime.now());
    }
    /**
     * 获取指定日期当周第一天的日期字符串,这里第一天为周一
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfWeekStr(LocalDateTime localDateTime) {
        return getFirstDayOfWeekStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期当周最后一天的日期字符串,这里最后一天为周日
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfWeekStr(LocalDateTime localDateTime) {
        return getLastDayOfWeekStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期当周第一天的日期字符串,这里第一天为周一,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getFirstDayOfWeekStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(DayOfWeek.MONDAY).withHour(0).withMinute(0).withSecond(0), pattern);
    }
    /**
     * 获取指定日期当周最后一天的日期字符串,这里最后一天为周日,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getLastDayOfWeekStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.with(DayOfWeek.SUNDAY).withHour(23).withMinute(59).withSecond(59), pattern);
    }
    /**
     * 获取今天开始时间的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getStartTimeOfDayStr() {
        return getStartTimeOfDayStr(LocalDateTime.now());
    }
    /**
     * 获取今天结束时间的日期字符串
     *
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getEndTimeOfDayStr() {
        return getEndTimeOfDayStr(LocalDateTime.now());
    }
    /**
     * 获取指定日期开始时间的日期字符串
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 00:00:00
     */
    public static String getStartTimeOfDayStr(LocalDateTime localDateTime) {
        return getStartTimeOfDayStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期结束时间的日期字符串
     *
     * @param localDateTime 指定日期时间
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getEndTimeOfDayStr(LocalDateTime localDateTime) {
        return getEndTimeOfDayStr(localDateTime, DATETIME_PATTERN);
    }
    /**
     * 获取指定日期开始时间的日期字符串,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd HH:mm:ss
     */
    public static String getStartTimeOfDayStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withHour(0).withMinute(0).withSecond(0), pattern);
    }
    /**
     * 获取指定日期结束时间的日期字符串,带日期格式化参数
     *
     * @param localDateTime 指定日期时间
     * @param pattern       日期时间格式
     * @return String 格式:yyyy-MM-dd 23:59:59
     */
    public static String getEndTimeOfDayStr(LocalDateTime localDateTime, String pattern) {
        return format(localDateTime.withHour(23).withMinute(59).withSecond(59), pattern);
    }
    /**
     * 切割日期。按照周期切割成小段日期段。例如: <br>
     *
     * @param startDate 开始日期(yyyy-MM-dd)
     * @param endDate   结束日期(yyyy-MM-dd)
     * @param period    周期(天,周,月,年)
     * @return 切割之后的日期集合
     * <li>startDate="2019-02-28",endDate="2019-03-05",period="day"</li>
     * <li>结果为:[2019-02-28, 2019-03-01, 2019-03-02, 2019-03-03, 2019-03-04, 2019-03-05]</li><br>
     * <li>startDate="2019-02-28",endDate="2019-03-25",period="week"</li>
     * <li>结果为:[2019-02-28,2019-03-06, 2019-03-07,2019-03-13, 2019-03-14,2019-03-20,
     * 2019-03-21,2019-03-25]</li><br>
     * <li>startDate="2019-02-28",endDate="2019-05-25",period="month"</li>
     * <li>结果为:[2019-02-28,2019-02-28, 2019-03-01,2019-03-31, 2019-04-01,2019-04-30,
     * 2019-05-01,2019-05-25]</li><br>
     * <li>startDate="2019-02-28",endDate="2020-05-25",period="year"</li>
     * <li>结果为:[2019-02-28,2019-12-31, 2020-01-01,2020-05-25]</li><br>
     */
    public static List<String> listDateStrs(String startDate, String endDate, String period) {
        List<String> result = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_PATTERN);
        LocalDate end = LocalDate.parse(endDate, dateTimeFormatter);
        LocalDate start = LocalDate.parse(startDate, dateTimeFormatter);
        LocalDate tmp = start;
        switch (period) {
            case DAY:
                while (start.isBefore(end) || start.isEqual(end)) {
                    result.add(start.toString());
                    start = start.plusDays(1);
                }
                break;
            case WEEK:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    if (tmp.plusDays(6).isAfter(end)) {
                        result.add(tmp.toString() + "," + end);
                    } else {
                        result.add(tmp.toString() + "," + tmp.plusDays(6));
                    }
                    tmp = tmp.plusDays(7);
                }
                break;
            case MONTH:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    LocalDate lastDayOfMonth = tmp.with(TemporalAdjusters.lastDayOfMonth());
                    if (lastDayOfMonth.isAfter(end)) {
                        result.add(tmp.toString() + "," + end);
                    } else {
                        result.add(tmp.toString() + "," + lastDayOfMonth);
                    }
                    tmp = lastDayOfMonth.plusDays(1);
                }
                break;
            case YEAR:
                while (tmp.isBefore(end) || tmp.isEqual(end)) {
                    LocalDate lastDayOfYear = tmp.with(TemporalAdjusters.lastDayOfYear());
                    if (lastDayOfYear.isAfter(end)) {
                        result.add(tmp.toString() + "," + end);
                    } else {
                        result.add(tmp.toString() + "," + lastDayOfYear);
                    }
                    tmp = lastDayOfYear.plusDays(1);
                }
                break;
            default:
                break;
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(getLocalDateTimeStr());
        System.out.println(getLocalDateStr());
        System.out.println(getLocalTimeStr());
        System.out.println(getDayOfWeekStr());
        System.out.println(getDayOfWeekStr(LocalDate.now()));
        System.out.println("========");
        System.out.println(format(LocalDate.now(), UNSIGNED_DATE_PATTERN));
        System.out.println("========");
        System.out.println(parseLocalDateTime("2020-12-13 11:14:12", DATETIME_PATTERN));
        System.out.println(parseLocalDate("2020-12-13", DATE_PATTERN));
        System.out.println("========");
        System.out.println(plus(LocalDateTime.now(), 3, ChronoUnit.HOURS));
        System.out.println(minus(LocalDateTime.now(), 4, ChronoUnit.DAYS));
        System.out.println("========");
        System.out.println(getChronoUnitBetween(LocalDateTime.now(), parseLocalDateTime("2020-12-12 12:03:12", DATETIME_PATTERN), ChronoUnit.MINUTES));
        System.out.println(getChronoUnitBetween(LocalDate.now(), parseLocalDate("2021-12-12", DATE_PATTERN), ChronoUnit.WEEKS));
        System.out.println("========");
        System.out.println(getFirstDayOfYearStr());
        System.out.println(getFirstDayOfYearStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getFirstDayOfYearStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println(getLastDayOfYearStr());
        System.out.println(getLastDayOfYearStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getLastDayOfYearStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println("========");
        System.out.println(getFirstDayOfMonthStr());
        System.out.println(getFirstDayOfMonthStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getFirstDayOfMonthStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println(getLastDayOfMonthStr());
        System.out.println(getLastDayOfMonthStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getLastDayOfMonthStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println("========");
        System.out.println(getFirstDayOfWeekStr());
        System.out.println(getFirstDayOfWeekStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getFirstDayOfWeekStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println(getLastDayOfWeekStr());
        System.out.println(getLastDayOfWeekStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getLastDayOfWeekStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println("========");
        System.out.println(getStartTimeOfDayStr());
        System.out.println(getStartTimeOfDayStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getStartTimeOfDayStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println(getEndTimeOfDayStr());
        System.out.println(getEndTimeOfDayStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN)));
        System.out.println(getEndTimeOfDayStr(parseLocalDateTime("2021-12-12 12:03:12", DATETIME_PATTERN), UNSIGNED_DATETIME_PATTERN));
        System.out.println("========");
        List<String> dateStrs = listDateStrs("2019-01-30", "2020-12-13", YEAR);
        for (String dateStr : dateStrs) {
            System.out.println(dateStr);
        }
        System.out.println("========");
        List<String> dateStrs1 = listDateStrs("2019-01-30", "2020-12-13", MONTH);
        for (String dateStr : dateStrs1) {
            System.out.println(dateStr);
        }
        System.out.println("========");
        List<String> dateStrs2 = listDateStrs("2020-12-01", "2020-12-13", DAY);
        for (String dateStr : dateStrs2) {
            System.out.println(dateStr);
        }
    }
}

第三种

package com....;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
 * @version V1.0
 * @File: DateUtils
 * @Description: 常用的时间处理方法集合工具类
 * @author: aitree
 */
public class DateUtils {
    /**
     * 时间格式常量
     */
    public static final String COMMON_PATTERN       = "yyyy-MM-dd HH:mm:ss";
    public static final String COMMON_PATTERN_TYPE2 = "yyyy/MM/dd HH:mm:ss";
    public static final String SHORT_PATTERN        = "yyyy-MM-dd";
    public static final String SHORT_PATTERN_TYPE2  = "yyyy/MM/dd";
    public static final String LONG_PATTERN         = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String SUP_SHORT_PATTERN    = "yyyyMMdd";
    public static final String SUP_LONG_PATTERN     = "yyyyMMddHHmmss";
    public static final String YEAR_MONTH           = "yyyyMM";
    public static final String CN_SHORT_PATTERN     = "yyyy年MM月dd日";
    public static final String DDMM_PATTERN         = "ddMM";
    /**
     * 1、将 String 解析为 date
     *
     * @param dateString 待解析的日期字符串
     * @param pattern    日期字符串的时间格式
     * @return
     */
    public static Date trans2Date(String dateString, String pattern) {
        String fRTN = StringUtils.isNotBlank(pattern) ? pattern : COMMON_PATTERN;
        DateTimeFormatter format = DateTimeFormat.forPattern(fRTN);
        DateTime dt = DateTime.parse(dateString, format);
        return dt.toDate();
    }
    /**
     */2、日期字符串格式化输出
     *
     * @param dateString  待格式化的日期字符串
     * @param fromPattern 待格式化日期字符串的格式
     * @param toPattern   格式化后的日期格式
     * @return
     */
    public static String formatDate2String(String dateString, String fromPattern, String toPattern) {
        String tRTN = StringUtils.isNotBlank(toPattern) ? toPattern : COMMON_PATTERN;
        DateTimeFormatter format = DateTimeFormat.forPattern(fromPattern);
        DateTime dt = DateTime.parse(dateString, format);
        return dt.toString(tRTN);
    }
    /**
     * 3、Date类型日期转字符串格式化输出
     *
     * @param date    待格式化的日期
     * @param pattern 格式化后的格式
     * @return
     */
    public static String formatDate2String(Date date, String pattern) {
        String fRTN = StringUtils.isNotBlank(pattern) ? pattern : COMMON_PATTERN;
        DateTimeFormatter format = DateTimeFormat.forPattern(fRTN);
        return new DateTime(date).toString(format);
    }
    /**
     * 4、增加天数后的Date日期
     *
     * @param date      起点日期(date/string)
     * @param daysCount 增加天数
     * @return
     */
    public static <T> Date add(T date, int daysCount) {
        DateTime dt = new DateTime(date);
        return dt.plusDays(daysCount).toDate();
    }
    /**
     * 5、计算日期{@link Date}增加某天数后的Date类型日期
     *
     * @param d           Date
     * @param amountToAdd 天数增加值
     * @return Date
     */
    public static Date plusDays(Date d, long amountToAdd) {
         return toDate(plusDays(toLocalDateTime(d), amountToAdd));
    }
    public static LocalDateTime plusDays(LocalDateTime ldt, long amountToAdd) {
         return ldt.plusDays(amountToAdd);
    }
    /**
     *6、减少天数后的日期
     *
     * @param date      起点日期(date/string)
     * @param daysCount 减少的天数
     * @return
     */
    public static <T> Date sub(T date, int daysCount) {
        DateTime dt = new DateTime(date);
        return dt.minusDays(daysCount).toDate();
    }
    /**
     * 7、增加月数后的日期
     *
     * @param date      起点日期(date/string)
     * @param months    增加月数
     * @return
     */
    public static <T> Date addMonths(T date, int months) {
        DateTime dt = new DateTime(date);
        return dt.plusMonths(months).toDate();
    }
    /**
     */8、减少月数后的日期
     *
     * @param date      起点日期(date/string)
     * @param months    减少的月数
     * @return
     */
    public static <T> Date subMonths(T date, int months) {
        DateTime dt = new DateTime(date);
        return dt.minusMonths(months).toDate();
    }
    /**
     */9、减少年数后的日期
     *
     * @param date      起点日期(date/string)
     * @param years     减少的年数
     * @return
     */
    public static <T> Date subYears(T date, int years) {
        DateTime dt = new DateTime(date);
        return dt.minusYears(years).toDate();
    }
    /**
     * 10、计算月份差
     * @param lastRepaymentDate
     * @param fundLoanDate
     * @return
     */
    public static int getMonthParse(String lastRepaymentDate, String fundLoanDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(sdf.parse(fundLoanDate));
        aft.setTime(sdf.parse(lastRepaymentDate));
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR))*12;
        return month+result;
    }
    /**
     * 11、计算两个日期的间隔天数
     * 目前不对两个日期比较大小,如放错顺序,则结果为负数的天数
     *
     * @param dateMin 起点日期(date/string)
     * @param dateMax 结束日期(date/string)
     * @return
     */
    public static <T> int betweenDays(T dateMin, T dateMax) {
        LocalDate start = new LocalDate(dateMin);
        LocalDate end = new LocalDate(dateMax);
        return Days.daysBetween(start, end).getDays();
    }
    /**
     * 12、计算两个时间的毫秒间隔
     * 目前不对两个时间参数比较大小,如放错顺序,则结果为负数的毫秒间隔
     *
     * @param dateMin 起点日期(date/string)
     * @param dateMax 结束日期(date/string)
     * @return
     */
    public static <T> long betweenMs(T dateMin, T dateMax) {
        DateTime start = new DateTime(dateMin);
        DateTime end = new DateTime(dateMax);
        return end.getMillis() - start.getMillis();
    }
    /**
     * 13、判断是否为交易日/工作日
     *
     * @param date 待判断日期(date/string)
     * @return
     */
    public static <T> boolean isTradeDay(T date) {
        boolean isTD = false;
        DateTime dt = new DateTime(date);
        if (isSpWorkDay(dt) || (!isHoliday(dt) && !isWeekEnd(dt))) {
            isTD = true;
        }
        return isTD;
    }
    //14、判断是否是周末*/
    private static boolean isWeekEnd(DateTime dt) {
        boolean isWE = false;
        int wd = dt.dayOfWeek().get();
        switch (wd) {
            case 6:
            case 7:
                isWE = true;
                break;
            default:
                break;
        }
        return isWE;
    }
    //15、判断是否为国家法定节假日*/
    private static boolean isHoliday(DateTime dt) {
        boolean isHD = false;
        //TODO:get days from redis
        List<String> holidayList = new ArrayList<String>();
        if (holidayList != null) {
            for (String holiday : holidayList) {
                if (dt.isEqual(new DateTime(holiday))) {
                    isHD = true;
                    break;
                }
            }
        }
        return isHD;
    }
    //16、判断是否为国家调整后的工作日*/
    private static boolean isSpWorkDay(DateTime dt) {
        boolean isSpWD = false;
        //TODO:get days from redis
        List<String> spWorkDayList = new ArrayList<String>();
        if (spWorkDayList != null) {
            for (String spWorkDay : spWorkDayList) {
                if (dt.isEqual(new DateTime(spWorkDay))) {
                    isSpWD = true;
                    break;
                }
            }
        }
        return isSpWD;
    }
    /**
     */17、获得时间指定时间差值 日期
     * @param: aDate
     * @param: field 查看  Calendar.MINUTE  、SECOND
     * @param: diff 时间差
     * @return:
     */
    public static final Date diffDate(Date aDate, int field, int diff) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(aDate);
        cal.add(field, diff);
        return cal.getTime();
    }
    /**
     * 18、判断目标时间是否在区间内
     * @param sDate 开始时间date/string
     * @param eDate 结束时间date/string
     * @param cDate 目标时间date/string
     * @param <T>
     * @return
     */
    public static <T> boolean isInRange(T sDate, T eDate, T cDate){
        DateTime dtLow = new DateTime(sDate);
        DateTime dtHigh = new DateTime(eDate);
        DateTime dt = new DateTime(cDate);
        if(dt.getMillis()>=dtLow.getMillis() && dt.getMillis()<=dtHigh.getMillis()){
            return true;
        }
        return false;
    }
    public static <T> boolean isInRange(){
        DateTime now = DateTime.now();
        return isInRange(now,now,now);
    }
    public static <T> boolean isInRange(T sDate, T eDate){
        DateTime now = DateTime.now();
        return isInRange(sDate,eDate,now);
    }
   /**
    * 19、获取当前8位系统日期
    *
    * @return yyyyMMdd
    */
   public static String getCurrentDateStr() {
       return format(LocalDate.now());
   }
   /**
    */20、获取当前6位系统时间
    *
    * @return HHmmss
    */
   public static String getCurrentTimeStr() {
       return format(LocalTime.now());
   }
   /**
    */21、获取当前14位系统日期时间
    *
    * @return yyyyMMddHHmmss
    */
   public static String getCurrentDateTimeStr() {
       return format(LocalDateTime.now());
   }
   /**
    */22、按指定格式获取当前系统日期时间
    *
    * @param pattern pattern
    * @return 格式化的当前系统日期时间
    */
   public static String getCurrentDateTimeStr(String pattern) {
      return format(LocalDateTime.now(), pattern);
   }
   /**
   */23、获取字符串start到end天数间隔
   *
   * @param start 开始日期,YYYYMMDD
   * @param end   结束日期,YYYYMMDD
   * @return 天数间隔
   */
   public static long getDaysBetweenDate(String start, String end) {
       return toLocalDate(start).until(toLocalDate(end), ChronoUnit.DAYS);
   }  
   /**
    */24、获取Date日期类型start到end天数间隔
    *
    * @param start 开始日期
    * @param end   结束日期
    * @return 天数间隔
    */
   public static long getDaysBetween(Date start, Date end) {
       return getDaysBetween(toLocalDate(start), toLocalDate(end));
   }
   public static LocalDate toLocalDate(Date d) {
      return toLocalDateTime(d).toLocalDate();
   }
}

以上就是Java8中常用的日期时间工具类总结的详细内容,更多关于Java8日期时间工具类的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文