java计算两个时间的差距

本文介绍如何使用Java计算两个日期或时间之间的差距,包括年、月、日、时、分、秒等不同单位,并提供具体代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java计算两个时间的差距

直接看代码吧

 public static void main(String[] args) {
        // 计算两个日期之间差了多少年、多少月、多少日,此结果为组合使用
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse("2020-12-31", dateFormatter);
        LocalDate endDate = LocalDate.parse("2021-01-01", dateFormatter);
        Period between = Period.between(startDate, endDate);
        // 用此类也是一样的效果
        // ChronoUnit.DAYS.between(startDate, endDate);
        System.out.printf("差距 %s 年 ,%s 月, %s 日 \n", between.getYears(), between.getMonths(), between.getDays());

        // 计算两个时间之间差了多少年、多少月、多少日,多少时,多少分,多少秒,此方法为单独计算
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse("2020-12-31 01:23:23", dateTimeFormatter);
        LocalDateTime endTime = LocalDateTime.parse("2021-12-30 12:23:23", dateTimeFormatter);
        Duration duration = Duration.between(startTime, endTime);
        System.out.printf("差距%s 年 ,%s 月, %s 日, %s 时 ,%s 分, %s 秒 \n",
                startTime.until(endTime, ChronoUnit.YEARS),
                startTime.until(endTime, ChronoUnit.MONTHS),
                startTime.until(endTime, ChronoUnit.DAYS),
                startTime.until(endTime, ChronoUnit.HOURS),
                startTime.until(endTime, ChronoUnit.MINUTES),
                startTime.until(endTime, ChronoUnit.SECONDS));


    }



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值