java计算两个日期间相差的天数/小时数/分钟数,并保留N位小数

  • Post author:
  • Post category:java

原文地址:【java计算两个日期间相差的天数/小时数/分钟数,并保留N位小数】_程序媛_文乐的博客-CSDN博客_java计算时间差小时

以计算两个日期之间的小时数为例
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 void ShowTimeInterval(Date date1, Date date2) {
 long lDate1 = date1.getTime();

long lDate2 = date2.getTime();

 long diff = (lDate1 < lDate2) ? (lDate2 – lDate1) : (lDate1 – lDate2);

 long day = diff / (24 * 60 * 60 * 1000);

 long hour = diff / (60 * 60 * 1000) – day * 24;

 long min = diff / (60 * 1000) – day * 24 * 60 – hour * 60;
 
 long sec = diff / 1000 – day * 24 * 60 * 60 – hour * 60 * 60 – min * 60;

 System.out.println(“date1 与 date2 相差 ” + day + “天” + hour + “小时” + min + “分” + sec + “秒”);
 }