java实现天数差简便方法

话不多说,直接撸代码!

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值