@Override
public Integer computHours(DateVo vo) throws ParseException {
//如果不足一个小时,按一个小时计算,如果超出整小时部分,加1
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String beginStr = String.format("%s %s", vo.getMeetDate(), vo.getBeginTime());
String endStr = String.format("%s %s", vo.getMeetDate(), vo.getEndTime());
Date beginTime = dateFormat.parse(beginStr);
Date endTime = dateFormat.parse(endStr);
long diff = endTime.getTime() - beginTime.getTime();
long minutes = diff / (1000 * 60);
double hours = (double)minutes / 60;
double ceil = Math.ceil(hours);
Integer result = new Double(ceil).intValue();
return result;
}
测试:
@Test
public void testHours(){
DateVo dateVo1 = new DateVo();
dateVo1.setMeetDate("2022-03-27");
dateVo1.setBeginTime("14:57");
dateVo1.setEndTime("16:57");
try {
Integer hour1 = orderService.computHours(dateVo1);
log.info("实际整两个小时,应为 2 = {}",hour1);
} catch (ParseException e) {
e.printStackTrace();
}
DateVo dateVo2 = new DateVo();
dateVo2.setMeetDate("2022-03-27");
dateVo2.setBeginTime("14:57");
dateVo2.setEndTime("15:27");
try {
Integer hour2 = orderService.computHours(dateVo2);
log.info("实际 30 分钟,应为 1 = {}",hour2);
} catch (ParseException e) {
e.printStackTrace();
}
DateVo dateVo3 = new DateVo();
dateVo3.setMeetDate("2022-03-27");
dateVo3.setBeginTime("14:57");
dateVo3.setEndTime("16:27");
try {
Integer hour3 = orderService.computHours(dateVo3);
log.info("实际 一个小时 30分钟,应为 2 = {}",hour3);
} catch (ParseException e) {
e.printStackTrace();
}
}
知识备注:
Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数。