java 日期只计算年月日大小_Java 计算两个日期相差多少年月日
JDK7及以前的版本,計(jì)算兩個(gè)日期相差的年月日比較麻煩。
JDK8新出的日期類,提供了比較簡(jiǎn)單的實(shí)現(xiàn)方法。
/*** 計(jì)算2個(gè)日期之間相差的 相差多少年月日
* 比如:2011-02-02 到 2017-03-02 相差 6年,1個(gè)月,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();
}
一個(gè)簡(jiǎn)單的工具方法,供參考。
簡(jiǎn)要說2點(diǎn):
1. LocalDate.parse(dateString)?這個(gè)是將字符串類型的日期轉(zhuǎn)化為L(zhǎng)ocalDate類型的日期,默認(rèn)是DateTimeFormatter.ISO_LOCAL_DATE即YYYY-MM-DD。
LocalDate還有個(gè)方法是parse(CharSequence text, DateTimeFormatter formatter),帶日期格式參數(shù),下面是JDK中的源碼,比較簡(jiǎn)單,不多說了,感興趣的可以自己去看一下源碼
/*** 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計(jì)算時(shí)間差,Period類內(nèi)置了很多日期計(jì)算方法,感興趣的可以去看源碼。Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));主要也是用LocalDate去做計(jì)算。Period可以快速取出年月日等數(shù)據(jù)。
3. 使用舊的Date對(duì)象時(shí),我們用SimpleDateFormat進(jìn)行格式化顯示。使用新的LocalDateTime或ZonedLocalDateTime時(shí),我們要進(jìn)行格式化顯示,就要使用DateTimeFormatter。
和SimpleDateFormat不同的是,DateTimeFormatter不但是不變對(duì)象,它還是線程安全的。線程的概念我們會(huì)在后面涉及到。現(xiàn)在我們只需要記住:因?yàn)镾impleDateFormat不是線程安全的,使用的時(shí)候,只能在方法內(nèi)部創(chuàng)建新的局部變量。而DateTimeFormatter可以只創(chuàng)建一個(gè)實(shí)例,到處引用。
創(chuàng)建DateTimeFormatter時(shí),我們?nèi)匀煌ㄟ^傳入格式化字符串實(shí)現(xiàn):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
格式化字符串的使用方式與SimpleDateFormat完全一致。
總結(jié)
以上是生活随笔為你收集整理的java 日期只计算年月日大小_Java 计算两个日期相差多少年月日的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 跳添加编辑页面传两个值_vue两
- 下一篇: (递归5)全排列