使用SimpleDateFormat对两个日期做减法
1.背景
实际项目开发中,经常遇到对两个Date类型的时间进行相减,得到一个时间差,这个时间差的类型可能是"HH:mm:ss"、“dd HH:mm:ss”。
2.代码示例
String start = "2010-2-2 01:01:01";
String end = "2010-2-2 03:03:03";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
// 设置时区不生效。 设置时区的目的在于纠正八小时时间差。
//impleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date startTime = simpleDateFormat.parse(start);
Date endTime = simpleDateFormat.parse(end);
System.out.println(simpleDateFormat.format(startTime));
long startTimeMills = startTime.getTime();
long endTimeMills = endTime.getTime();
long curTimeMills = System.currentTimeMillis();
// 再减去八小时的毫秒数。
Date date = new Date(endTimeMills - startTimeMills - 28800000L);
String time = simpleDateFormat2.format(date);
System.out.println(time);
使用LocalDateTime对两个日期做减法(推荐)-更优雅
String start = "2010-02-02 01:01:01";
String end = "2010-02-02 03:03:03";
LocalDateTime startDateTime = LocalDateTime.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime endDateTime = LocalDateTime.parse(end, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Duration duration = Duration.between(startDateTime, endDateTime);
System.out.println(LocalTime.ofNanoOfDay(duration.toNanos()).format(DateTimeFormatter.ofPattern("HH:mm:ss")));