计算LocalDateTime相差的天数,24小时为单位,取模计算

2024-10-09 11:28:10 浏览数 (1)

计算LocalDateTime相差的天数,24小时为单位,取模计算

代码语言:javascript复制
package com.example.core.mydemo.java2;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeTest {
    public static void main(String[] args) {
        LocalDateTime dateTime1 = LocalDateTime.of(2024, 7, 1, 12, 0);
        LocalDateTime dateTime2 = LocalDateTime.of(2024, 7, 3, 11, 0);

//        long daysBetween = ChronoUnit.DAYS.between(dateTime1, dateTime2);

        long daysBetween = 1; //默认
        long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
        System.out.println("相差小时数: "   hoursBetween);
        System.out.println("11="   (hoursBetween / 24));
        System.out.println("11="   (hoursBetween % 24));
        if(hoursBetween <= 24){
            daysBetween = 1;
        }else {
            if (hoursBetween % 24 == 0){
                daysBetween = (hoursBetween / 24 );
            }else{
                daysBetween = (hoursBetween / 24 )   1;
            }
        }
        System.out.println("相差天数: "   daysBetween);

    }
}

0 人点赞