计算两个日期之间的时间差、累计时长,精确到秒

来源:互联网 发布:网络新技术概论 编辑:程序博客网 时间:2024/05/14 22:56
/* * 计算时间间隔,精确到秒,返回一个String */public String caculateDuration(Date beginDate, Date endDate) {Long beginDateLong = beginDate.getTime();// Date型转换成Long型毫秒数,用于计算Long endDateLong = endDate.getTime();Long durationLong = endDateLong - beginDateLong;long totalSeconds = durationLong / 1000;// 总共的秒数long secondsOfDay = 24 * 60 * 60;// 一天的秒数long secondsOfHour = 60 * 60; // 一小时的秒数long secondsOfMinute = 60; // 一分钟的秒数long days = totalSeconds / secondsOfDay;// 得到天数long hours = (totalSeconds % secondsOfDay) / secondsOfHour;// 余数中的小时个数long minutes = ((totalSeconds % secondsOfDay) % secondsOfHour) / secondsOfMinute; // 余数中的分钟数long seconds = totalSeconds % 60;// 余数中的秒数return days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";}
调用:Date nowDate = new Date();//获取当前系统时间Date errorDate = errorRecord.getErrorDate();//获取故障发生时间String duration = otdrService.caculateDuration(errorDate, nowDate);//根据两个日期计算时差、累计时长

0 0