java新特性處理時間工具類

浪丶蕩發表於2019-01-07
package cn.com.hongyitech.accountsystem.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Description: 新特性的時間處理工具類
 * @Author: hl
 * @CreateDate: 2019/1/7 9:33
 * @UpdateUser: hl
 * @UpdateDate: 2019/1/7 9:33
 * @UpdateRemark: 修改內容
 * @Version: 1.0
 * 適用jdk 8及以上版本
 */
public class DateUtil {

    /**
     * 根據傳入的日期獲取字串形式的年月日
     * date--->【yyyy-mm-dd】
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 9:34
     */
    public static String dateToYMD(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        LocalDate localDate = localDateTime.toLocalDate();
        return localDate.toString();
    }

    /**
     * 根據傳入的日期格式化成需要的樣式
     *
     * @return yyyy-MM-dd HH:mm:ss
     * @throws
     * @author hl
     * @date 2019/1/7 9:46
     */
    public static String dateToYMDHMS(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTimeFormater.format(localDateTime);
    }

    /**
     * 根據傳入的日期格式化成需要的樣式
     *
     * @return yyyy年MM月dd日hh時mm分ss秒
     * @throws
     * @author hl
     * @date 2019/1/7 9:49
     */
    public static String dateToYMDhms(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH時mm分ss秒");
        return dateTimeFormater.format(localDateTime);
    }

    public static String date2YMDhms(Date date) {
        return date2YMDhmsss(date);
    }

    /**
     * 根據傳入的日期轉成帶毫秒值的字串格式
     *
     * @return yyyyMMddhhmmssSSS
     * @throws
     * @author hl
     * @date 2019/1/7 9:52
     */
    public static String date2YMDhmsss(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        return dateTimeFormater.format(localDateTime);
    }

    /**
     * 字串形式日期轉換成標準日期 String --> Date "yyyy-MM-dd"-->yyyy-MM-dd
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 9:55
     */
    public static LocalDate YMDToDate(String date) {

        return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    /**
     * 字串形式日期轉換成標準日期 String --> Date "yyyy-MM-dd HH:mm:ss"-->yyyy-MM-dd HH:mm:ss
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:24
     */
    public static LocalDateTime YMDHMSToDate(String date) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(date, df);
    }

    /**
     * Date轉LocalDateTime
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:35
     */
    public static LocalDateTime DateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    /**
     * LocalDateTime轉Date
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:35
     */
    public static Date DateTime2Date(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return Date.from(instant);
    }

    /**
     * LocalDateTime轉LocalDate
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:40
     */
    public static LocalDate LocalDateTimeToLocalDate(LocalDateTime localDateTime) {
        return localDateTime.toLocalDate();

    }

    /**
     * 獲取當前日期的年
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:48
     */
    public static String getTheYear() {
        return Integer.toString(LocalDate.now().getYear());
    }

    /**
     * 字串轉LocalDateTime
     * 比如yyyy-mm-dd HH:mm:ss 轉LocalDateTime
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:55
     */
    public static LocalDateTime localDateTimeParse(String time, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(time, df);
    }

    /**
     * 判斷兩個時間之間的間隔分鐘數是否大於某個值,大於返回true
     * 時間格式必須是yyyy-mm-dd HH:mm:ss
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 10:50
     */
    public static boolean checkBwintervalNumberMinBegTmAndEndTm(String begTm, String endTm, int intervalNumber) {
        Long minutesBetween = getMinutesBetween(begTm, endTm);
        Long intervalNumberLong = new Long(intervalNumber);
        return minutesBetween.longValue() >= intervalNumberLong.longValue() ? true : false;
    }

    /**
     * 起始時間與結束時間間隔不能少於40分鐘
     *
     * @return 開始+40分鐘<結束返回true
     * @throws
     * @author hl
     * @date 2019/1/7 11:34
     */
    public static boolean checkBw40MinBegTmAndEndTm(String begTm, String endTm) {
        return checkBwintervalNumberMinBegTmAndEndTm(begTm, endTm, 40);
    }

    /**
     * 判斷兩個字串時間之間相隔的分鐘數,如果為負數,說明前面的時間比後面的時間要晚
     * 時間格式必須是yyyy-mm-dd HH:mm:ss
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 11:01
     */
    public static Long getMinutesBetween(String begTm, String endTm) {
        LocalDateTime start = localDateTimeParse(begTm, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime end = localDateTimeParse(endTm, "yyyy-MM-dd HH:mm:ss");
        Duration between = Duration.between(start, end);
        return between.toMinutes();//相差分鐘數
    }

  /**
   *  比較兩個時間的大小
   *  時間格式必須是yyyy-mm-dd HH:mm:ss
   * @author      hl
   * @return 開始<結束返回 true
   */
    public static boolean checkBegTmAndEndTm(String begTm, String endTm) {
        LocalDateTime start = localDateTimeParse(begTm, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime end = localDateTimeParse(endTm, "yyyy-MM-dd HH:mm:ss");
        return start.compareTo(end) < 0 ? true : false;
    }

    /**
     * 獲取指定日期後一星期的字串格式日期
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 12:02
     */
    public static String getAfterWeekDateYMDHMS(Date date) {
        LocalDateTime localDateTime = DateToLocalDateTime(date);
        LocalDateTime AfterWeek = localDateTime.plusDays(7);
        return localDateTime2YMDHMS(AfterWeek);
    }

    /**
     * localDateTime2YMDHMS
     * 返回的格式為 yyyy-MM-dd HH:mm:ss
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 12:04
     */
    public static String localDateTime2YMDHMS(LocalDateTime localDateTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return df.format(localDateTime);
    }

    /**
     * 計算兩個日期之間的間隔天數,只取整數部分
     * 時間格式必須是yyyy-mm-dd HH:mm:ss
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 11:40
     */
    public static int checkDaysBegTmAndEndTm(String begTm, String endTm) {
        LocalDateTime start = localDateTimeParse(begTm, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime end = localDateTimeParse(endTm, "yyyy-MM-dd HH:mm:ss");
        Duration between = Duration.between(start, end);
        int betweenDays = (int) between.toDays();
        return Math.abs(betweenDays);
    }

    /**
     * 獲取兩個時間的時間差(小時)
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 13:48
     */
    public static int getHourFromTwoTime(String begTm, String endTm) {
        LocalDateTime start = localDateTimeParse(begTm, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime end = localDateTimeParse(endTm, "yyyy-MM-dd HH:mm:ss");
        Duration between = Duration.between(start, end);
        int betweenDays = (int) between.toHours();
        return Math.abs(betweenDays);
    }

    /**
     * 返回指定時間的零時零分零秒的時間
     *
     * @param date
     * @return yyyy-MM-dd 00:00:00
     */
    public static String getBeforOneDateYMDHMS(Date date) {
        String str = dateToYMD(date);
        LocalDate localDate = LocalDate.parse(str);
        LocalDateTime localDateTime = localDate.atStartOfDay();
        DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTimeFormater.format(localDateTime);
    }

    /**
     * 返回指定時間的23點59分59秒
     *
     * @param date
     * @return yyyy-MM-dd 00:00:00
     */
    public static String getEndOneDateYMDHMS(Date date) {
        String str = dateToYMD(date);
        LocalDate localDate = LocalDate.parse(str);
        LocalDateTime localDateTime = localDate.atStartOfDay();
        localDateTime = localDateTime.plusHours(23);
        localDateTime = localDateTime.plusMinutes(59);
        localDateTime = localDateTime.plusSeconds(59);
        DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTimeFormater.format(localDateTime);
    }

    /**
     * 當前時間與begTm的前十分鐘的大小
     *
     * @return 兩個時間相隔的毫秒數
     * @throws
     * @author hl
     * @date 2019/1/7 12:47
     */
    public static long checkDaysBeforeTenMinuteCurrTmAndBegTm(String toDate, String begTm) {
        LocalDateTime localDateTime = localDateTimeParse(begTm, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime toDateLocalDateTime = localDateTimeParse(toDate, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTimeTenMinuteAfter = localDateTime.plusMinutes(10);
        Duration between = Duration.between(toDateLocalDateTime, localDateTimeTenMinuteAfter);
        return between.toMillis();
    }

    /**
     * 獲取指定日期yyyy-mm-dd HH:mm:ss的前後幾個月,前用負數表示2月份前的一個月就是-1
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 13:36
     */
    public static String getBeforSomeMonthFromCurrent(String currentTm, int month) {
        LocalDateTime localDateTime = localDateTimeParse(currentTm, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTimeBeforSomeMonth = localDateTime.plusMonths(month);
        return localDateTime2YMDHMS(localDateTimeBeforSomeMonth);
    }

    /**
     * 獲取當前時間前一個月的日期yyyy-mm-dd HH:mm:ss格式
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 13:44
     */
    public static String getBeforOneMonthFromCurrent() {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeBeforOneMonth = localDateTime.plusMonths(-1);
        return localDateTime2YMDHMS(localDateTimeBeforOneMonth);
    }

    /**
     * 獲取當前時間後一個月的日期yyyy-mm-dd HH:mm:ss格式
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 13:46
     */
    public static String getAfterOneMonthFromCurrent() {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeAfterOneMonth = localDateTime.plusMonths(1);
        return localDateTime2YMDHMS(localDateTimeAfterOneMonth);
    }

    /**
     * 獲取當前時間的幾個月之前或之後的時間值yyyy-mm-dd HH:mm:ss格式
     * 當前時間前傳負數,後傳正數
     *
     * @return
     * @throws
     * @author hl
     * @date 2019/1/7 13:58
     */
    public static String getBeforeSomeMonthFromCurrent(int month) {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeAfterOneMonth = localDateTime.plusMonths(month);
        return localDateTime2YMDHMS(localDateTimeAfterOneMonth);
    }
    /**
     * 獲取當前時間後N個小時的字串時間
     * yyyy-mm-dd HH:mm:ss
     * @author      hl
     * @return
     * @exception
     * @date       2019/1/7 15:03
     */
    public static String getAfterTimeDateYMDHMS(int i) {
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeAdd = localDateTime.plusHours(i);
        return localDateTime2YMDHMS(localDateTimeAdd);
    }

    /**
     * @param str     需要校驗的時間字串 2018-09-10 或者2018-09-10 12:23:38
     * @param pattern 時間的格式 yyyy-MM-dd 或者yyyy-MM-dd HH:mm:ss(24小時制)
     * @return
     */
    public static boolean isValidDate(String str, String pattern) {
        boolean convertSuccess = true;
        // 指定日期格式為四位年/兩位月份/兩位日期,注意yyyy/MM/dd區分大小寫;
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            // 設定lenient為false.
            // 否則SimpleDateFormat會比較寬鬆地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就說明格式不對
            convertSuccess = false;
        }
        return convertSuccess;
    }

    public static void main(String[] args) {
        System.out.println("dateToYMD: " + dateToYMD(new Date()));
        System.out.println("dateToYMDHMS: " + dateToYMDHMS(new Date()));
        System.out.println("dateToYMDhms: " + dateToYMDhms(new Date()));
        System.out.println("date2YMDhmsss: " + date2YMDhmsss(new Date()));
        System.out.println("YMDToDate: " + YMDToDate("2019-01-07"));
        System.out.println("YMDHMSToDate: " + YMDHMSToDate("2019-01-07 00:00:09"));
        System.out.println("DateToLocalDateTime: " + DateToLocalDateTime(new Date()));
        System.out.println("DateTime2Date: " + DateTime2Date(LocalDateTime.now()));
        System.out.println("LocalDateTimeToLocalDate: " + LocalDateTimeToLocalDate(LocalDateTime.now()));
        System.out.println("getTheYear: " + getTheYear());
        System.out.println("localDateTimeParse: " + localDateTimeParse("2019-01-07 00:50:00", "yyyy-MM-dd HH:mm:ss"));
        System.out.println("checkBwintervalNumberMinBegTmAndEndTm: " + checkBwintervalNumberMinBegTmAndEndTm("2019-01-07 00:00:00", "2019-01-07 00:41:00", 40));
        System.out.println("checkBegTmAndEndTm: " + checkBegTmAndEndTm("2019-01-07 00:30:00", "2019-01-07 00:41:00"));
        System.out.println("checkDaysBegTmAndEndTm: " + checkDaysBegTmAndEndTm("2019-01-09 00:00:00", "2019-01-07 00:00:50"));
        System.out.println("getAfterWeekDateYMDHMS: " + getAfterWeekDateYMDHMS(new Date()));
        System.out.println("getBeforOneMonthFromCurrent: " + getBeforSomeMonthFromCurrent("2019-01-07 00:00:50", 1));
        System.out.println("getAfterOneMonthFromCurrent: " + getAfterOneMonthFromCurrent());
        System.out.println("getBeforOneMonthFromCurrent: " + getBeforOneMonthFromCurrent());
        System.out.println("getBeforOneDateYMDHMS: " + getBeforOneDateYMDHMS(new Date()));
        System.out.println("getBeforeSomeMonthFromCurrent: " + getBeforeSomeMonthFromCurrent(3));
        System.out.println("getHourFromTwoTime: " + getHourFromTwoTime("2019-01-09 00:00:00", "2019-01-07 00:00:50"));
        System.out.println("checkBw40MinBegTmAndEndTm: " + checkBw40MinBegTmAndEndTm("2019-01-09 00:00:00", "2019-01-07 00:00:50"));
        System.out.println("checkDaysBeforeTenMinuteCurrTmAndBegTm: " + checkDaysBeforeTenMinuteCurrTmAndBegTm("2019-01-07 00:00:50", "2019-01-07 00:00:50"));
        System.out.println("getEndOneDateYMDHMS: " + getEndOneDateYMDHMS(new Date()));
        System.out.println("isValidDate: " + isValidDate("2019-01-07 00:00:50", "yyyy-MM-dd HH:mm:ss"));


    }
}

附上一個不錯的教程地址:java.time包教程

相關文章