java 日期只计算年月日大小_Java 计算两个日期相差多少年月日
JDK7及以前的版本,計算兩個日期相差的年月日比較麻煩。
JDK8新出的日期類,提供了比較簡單的實現方法。
/*** 計算2個日期之間相差的 相差多少年月日
* 比如:2011-02-02 到 2017-03-02 相差 6年,1個月,0天
*@paramfromDate YYYY-MM-DD
*@paramtoDate YYYY-MM-DD
*@return年,月,日 例如 1,1,1*/
public staticString dayComparePrecise(String fromDate, String toDate){
Period period=Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));
StringBuffer sb= newStringBuffer();
sb.append(period.getYears()).append(",")
.append(period.getMonths()).append(",")
.append(period.getDays());returnsb.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 {@codeLocalDate} from a text string using a specific formatter.
*
* The text is parsed using the formatter, returning a date.
*
*@paramtext the text to parse, not null
*@paramformatter the formatter to use, not null
*@returnthe parsed local date, not null
*@throwsDateTimeParseException if the text cannot be parsed*/
public staticLocalDate parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter,"formatter");returnformatter.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完全一致。
總結
以上是生活随笔為你收集整理的java 日期只计算年月日大小_Java 计算两个日期相差多少年月日的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 跳添加编辑页面传两个值_vue两
- 下一篇: java 2d绘图 stroke_Jav