java怎麼計算兩個日期間隔的天,月,年
阿新 • • 發佈:2019-02-01
由昨天下班前的一段對話引出:
“A:折騰了一天,總算吧時間間距n個月演算法寫好了”
“B:出於經驗,calendar類或者是common.lang肯定有現成函式”
直接貼程式碼。
System.out.println(DurationFormatUtils.formatPeriod(new Date("2012/05/05").getTime(), new Date("2013/08/07").getTime(), "y-M-d"));
函式來自common.lang包,2.x-3.x都有實現。 可以將日期間距按指定的欄位需求做計算。
org.apache.commons.lang3.time.DurationFormatUtils Duration formatting utilities and constants. The following table describes the tokens used in the pattern language for formatting. character duration element y years M months d days H hours m minutes s seconds S milliseconds Since: 2.1 Version: $Id: DurationFormatUtils.java 1144993 2011-07-11 00:51:16Z ggregory $
這裡的經驗是,被提過10000次的需求。。肯定有現成解決方案,不要重複發明基礎輪子。 但是基於這個函式,到真正的業務需求(比如2個月3天,在業務裡面可能歸成3個月大小),做一些小邏輯封裝即可。