Java计算两个日期相差的年数、月数、天数。依赖工具类

文章介绍了如何借助Hutool工具类进行日期之间的差异计算,包括年、月、日的差值。通过示例代码展示了使用ChronoUnit和DateUtil的方法,如`ChronoUnit.YEAR.between()`和`DateUtil.betweenMonth()`,来计算两个日期之间的相差年数、月数和天数。
摘要由CSDN通过智能技术生成

1.借助hutool工具类

//引入包
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.10</version>
</dependency>

2.代码实现

String text1 = "2019-03-25";
Temporal startDate = LocalDate.parse(text1);
String text2 = "2022-05-30";
Temporal endDate = LocalDate.parse(text2);
//方法返回为相差年数
long year = ChronoUnit.YEAR.between(startDate, endDate);
System.out.println(year);
// 方法返回为相差月数
long month = ChronoUnit.MONTHS.between(startDate, endDate);
System.out.println(month);
//方法返回为相差天数
long day = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println(day);

3.Date格式时间计算

Date startDate = new Date(1553443200000L);
Date endDate = new Date(System.currentTimeMillis());
long betweenMonth = DateUtil.betweenMonth(startDate, endDate, true);
System.out.println(betweenMonth);
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值