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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM