话不多说,直接撸代码!

Timestamp currentTime = Timestamp.valueOf(LocalDateTime.now()); Timestamp createdTime = waybillMapper.getCreatedTime(); // 将Timestamp转换为Instant,以便进行时间差计算 Instant currentInstant = currentTime.toInstant(); Instant createdInstant = createdTime.toInstant(); // 计算时间差 Duration duration = Duration.between(createdInstant, currentInstant); // 获取天数差 long daysDifference = duration.toDays(); entity.setStorageGoodsDepositDay((int) daysDifference);//库存滞留天数
代码解释:
currentTime:当前天数
createdTime:被减数
daysDifference:天数差
计算结果就是当前时间减去指定时间,计算出天数差
方法很多,再推荐一种写法:

上代码:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse("2023-11-01");
Date date1 = formatter.parse("2022-11-01");
Instant currentInstant = date.toInstant();
Instant createdInstant = date1.toInstant();
// 计算时间差
Duration duration = Duration.between(createdInstant, currentInstant);
// 获取天数差
long daysDifference = duration.toDays();
System.out.println("两个日期之间的天数差为:" + daysDifference);
还有其他的写法:
LocalDate date1 = LocalDate.of(2021, 9, 1);
LocalDate date2 = LocalDate.of(2021, 9, 10);
long daysDifference = ChronoUnit.DAYS.between(date1, date2);
System.out.println("天数差:" + daysDifference);
文章介绍了在Java中如何通过多种方式计算两个时间点(如Timestamp、SimpleDateFormat、LocalDate)之间的天数差,包括使用Instant、Duration以及ChronoUnit等类进行日期处理。
7498

被折叠的 条评论
为什么被折叠?



