Java计算两个日期的时间差:XX天XX小时XX分钟XX秒
代码如下:
public static void main(String[] args) throws ParseException {
Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-01-01 00:00:01");
Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-01-03 00:00:00");
// 相差的毫秒值
Long milliseconds = endDate.getTime() - startDate.getTime();
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
long ns = 1000;// 一秒钟的毫秒数
long day = milliseconds / nd; // 计算相差多少天
long hour = milliseconds % nd / nh; // 计算相差剩余多少小时
long min = milliseconds % nd % nh / nm; // 计算相差剩余多少分钟
long sec = milliseconds % nd % nh % nm / ns; // 计算相差剩余多少秒
System.out.println("时间相差:" + day + "天" + hour + "小时" + min + "分钟" + sec + "秒");
// 时间相差:1天23小时59分钟59秒
long hourAll = milliseconds / nh; // 计算相差多少小时
System.out.println("时间相差:" + hourAll + "小时" + min + "分钟" + sec + "秒");
// 时间相差:47小时59分钟59秒
long min2 = milliseconds / nm; // 计算相差多少分钟
System.out.println("时间相差:" + min2 + "分钟" + sec + "秒");
// 时间相差:2879分钟59秒
}