無意中看到黑馬的視頻,jdk8后引入的標准庫Time把Date和Calendar兩個庫替代了,就學習了一下,果然方便了很多。
/** * 計算兩個日期之間的差值 * B-A * 更新JDK8的計算方法,更准確兼容性更好 * 顯然這個方法都不適合其他時區··· * */ public static long countDayToInt(String dateA, String dateB){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ return ChronoUnit.DAYS.between(LocalDate.parse(dateA),LocalDate.parse(dateB)); }else { String[] splitdate = dateA.split("-"); String[] splitdateB = dateB.split("-"); Calendar a = Calendar.getInstance(), b = Calendar.getInstance(); a.set(Integer.parseInt(splitdate[0]), Integer.parseInt(splitdate[1]) - 1, Integer.parseInt(splitdate[2])); b.set(Integer.parseInt(splitdateB[0]), Integer.parseInt(splitdateB[1]) - 1, Integer.parseInt(splitdateB[2])); return (b.getTimeInMillis() - a.getTimeInMillis()) / (1000 * 60 * 60 * 24); } }
另外在build.app中設置
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
大功告成!
如果要獲取現在的時間來進行計算也很簡單,直接使用
LocalDate.now()
如果你的應用支持多語言,而你的日期格式化是自己設定的,如2020-4-9這種形式的,你可以指定解析器:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); return ChronoUnit.DAYS.between(LocalDate.parse(dateA,formatter),LocalDate.parse(dateB,formatter));