以計算兩個日期之間的小時數爲例
public void mytest15() throws ParseException {
String startTime = "2019-11-08 10:12:00";
String endTime = "2019-11-08 17:23:00";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = dateFormat.parse(startTime);
Date endDate = dateFormat.parse(endTime);
Integer datePoor = getDatePoor(startDate,endDate);
BigDecimal b = new BigDecimal((double)datePoor/60);
Double hour = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();//第一個參數是保留小數的位數
System.out.println(hour);
}
public static Integer getDatePoor(Date startDate, Date endDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 獲得兩個時間的毫秒時間差異
long diff = endDate.getTime() - startDate.getTime();
// 計算差多少天
long day = diff / nd;
// 計算差多少小時
long hour = diff % nd / nh;
// 計算差多少分鐘
Long min = diff % nd % nh / nm;
// 計算差多少秒//輸出結果
// long sec = diff % nd % nh % nm / ns;
Long mymint = diff/1000/60;
int intValue = mymint.intValue();
return intValue;
}
執行程序,得到結果:7.18