Java计算两个Date之间相差的年月日

使用Period.between方法

		SimpleDateFormat formatter = new SimpleDateFormat(BaseConstants.Pattern.DATETIME);
        ParsePosition pos = new ParsePosition(0);
        Date date1 = formatter.parse("2021-11-16 17:50:54", pos);
        ParsePosition pos2 = new ParsePosition(0);
        Date date2 = formatter.parse("2027-01-06 06:50:54", pos2);

        //将Date类型转化为LocalDate
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = date1.toInstant();
        LocalDate localDate1 = instant.atZone(zoneId).toLocalDate();
        Instant instant2 = date2.toInstant();
        LocalDate localDate2 = instant2.atZone(zoneId).toLocalDate();

        Period period = Period.between(localDate1, localDate2);

        StringBuffer sb = new StringBuffer();
        System.out.println("相差年份:"+period.getYears());
        System.out.println("相差月份:"+period.getMonths());
        System.out.println("相差天数:"+period.getDays());

打印结果:
相差年份:5
相差月份:1
相差天数:21
不能使用通过DateFormat.getDateInstance()方法将Date转为LocalDate的原因为:

        String strDate1= DateFormat.getDateInstance().format(date1);
        String strDate2 = DateFormat.getDateInstance().format(date2);
        System.out.println("strDate1:"+strDate1);
        System.out.println("strDate2:"+strDate2);
        LocalDate Ldate1 = LocalDate.parse(strDate1);
        LocalDate Ldate2 = LocalDate.parse(strDate2);

打印结果:
strDate1:2021-11-16
strDate2:2027-1-6
报错:Text ‘2027-1-6’ could not be parsed at index 5

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值