1. 程式人生 > 實用技巧 >Java 計算兩個日期相差多少年月日

Java 計算兩個日期相差多少年月日

JDK7及以前的版本,計算兩個日期相差的年月日比較麻煩。

JDK8新出的日期類,提供了比較簡單的實現方法。

/**
     * 計算2個日期之間相差的  相差多少年月日
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1個月,0天
     * @param fromDate YYYY-MM-DD
     * @param toDate YYYY-MM-DD
     * @return 年,月,日 例如 1,1,1
     */
    public static String dayComparePrecise(String fromDate, String toDate){
        
        Period period 
= Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate)); StringBuffer sb = new StringBuffer(); sb.append(period.getYears()).append(",") .append(period.getMonths()).append(",") .append(period.getDays()); return sb.toString(); }

一個簡單的工具方法,供參考。

簡要說2點:

1. LocalDate.parse(dateString)這個是將字串型別的日期轉化為LocalDate型別的日期,預設是DateTimeFormatter.ISO_LOCAL_DATE即YYYY-MM-DD。

LocalDate還有個方法是parse(CharSequence text, DateTimeFormatter formatter),帶日期格式引數,下面是JDK中的原始碼,比較簡單,不多說了,感興趣的可以自己去看一下原始碼

 /**
     * Obtains an instance of {@code LocalDate} from a text string using a specific formatter.
     * <p>
     * The text is parsed using the formatter, returning a date.
     *
     * 
@param text the text to parse, not null * @param formatter the formatter to use, not null * @return the parsed local date, not null * @throws DateTimeParseException if the text cannot be parsed */ public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.parse(text, LocalDate::from); }

2. 利用Period計算時間差,Period類內建了很多日期計算方法,感興趣的可以去看原始碼。Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));主要也是用LocalDate去做計算。Period可以快速取出年月日等資料。

3. 使用舊的Date物件時,我們用SimpleDateFormat進行格式化顯示。使用新的LocalDateTimeZonedLocalDateTime時,我們要進行格式化顯示,就要使用DateTimeFormatter

SimpleDateFormat不同的是,DateTimeFormatter不但是不變物件,它還是執行緒安全的。執行緒的概念我們會在後面涉及到。現在我們只需要記住:因為SimpleDateFormat不是執行緒安全的,使用的時候,只能在方法內部建立新的區域性變數。而DateTimeFormatter可以只建立一個例項,到處引用。

建立DateTimeFormatter時,我們仍然通過傳入格式化字串實現:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

格式化字串的使用方式與SimpleDateFormat完全一致。

參考:https://blog.csdn.net/francislpx/article/details/88691386

https://www.liaoxuefeng.com/wiki/1252599548343744/1303985694703650