import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.Date; String strTime1 = "2020-12-04 12:20:20"; String strTime2 = "2020-12-03 14:20:20"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1; Date date2; try { date1 = format.parse(strTime1); date2 = format.parse(strTime2); 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 + "秒"); } catch (ParseException e) { e.printStackTrace(); }View Code
运行结果如下:
注:上述代码用于传入的两个时间为String类型的,如果传入时间直接为Date类型的,可做适当调整。
参考博客:
https://www.cnblogs.com/mforestlaw/p/3289414.html
标签:date1,相差,lDate1,long,60,计算,diff,Java,day From: https://www.cnblogs.com/daytoy105/p/16654848.html