计算两个时间之间相差的毫秒数

一:计算到天数(12-26——12-31相差天数毫秒数)

@Test
    void test33() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前月的最后一天
        LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());
        // 计算秒数
        long secondsUntilEndOfMonth = currentDate.until(lastDayOfMonth, ChronoUnit.DAYS) * 24 * 60 * 60;
        System.out.println("当前时间到当前月最后一天的秒数为:" + secondsUntilEndOfMonth + " 秒");
    }

效果:

二:计算到秒数(12月31日15时48分21秒——12月31日23时59分59秒相差天数毫秒数)

@Test
    void test34(){
        // 定义当前时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //当前时间
        String currentDate = sdf.format(new Date());
        //获取当前月最后一天
        LocalDate lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        //定义当前月最后一天时间格式
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String endDate =  dtf.format(lastDayOfMonth) + " 23:59:59";
        // 将字符串转换为LocalDateTime对象
        LocalDateTime currentDateTime = LocalDateTime.parse(currentDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endDateTime = LocalDateTime.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 计算两个时间的秒差异
        long secondDiff = ChronoUnit.SECONDS.between(currentDateTime, endDateTime);
        System.out.println("两个时间相差 " + secondDiff + " 秒。");
    }

效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Herbig

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值