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
進行格式化顯示。使用新的LocalDateTime
或ZonedLocalDateTime
時,我們要進行格式化顯示,就要使用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