今天遇到了个需求,需要计算时间差
然后本来想用下面这种写法的
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "天" + hour + "小时" + min + "分钟";
}
然后想了想,好像这么写有点傻,看起来不够高级
于是就使用calendar类来写了
如下:
public static void main(String[] args) throws ParseException {
Calendar nowCalendar = Calendar.getInstance();
nowCalendar.setTime(new Date());
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(org.apache.commons.lang3.time.DateUtils.parseDate("2019-09-29 00:00:00","yyyy-MM-dd HH:mm:ss"));
//计算天数
System.out.println(nowCalendar.get(Calendar.DAY_OF_MONTH) - startCalendar.get(Calendar.DAY_OF_MONTH));
//计算小时
System.out.println(nowCalendar.get(Calendar.HOUR_OF_DAY) - startCalendar.get(Calendar.HOUR_OF_DAY));
//计算分钟
System.out.println(nowCalendar.get(Calendar.MINUTE) - startCalendar.get(Calendar.MINUTE));
//计算秒
System.out.println(nowCalendar.get(Calendar.SECOND) - startCalendar.get(Calendar.SECOND));
}
结果:
1
19
3
28
其实就是Calendar封了一层(划掉
以上