java中LocalDateTime计算两个时间间隔,转换为时-分-秒

时间:2025-03-10 07:42:18

        利用Duration类可以轻松拿到两个LocalDateTime的时间间隔,可以获取到间隔的秒数,然后转换为时-分-秒:

public static void main(String[] args) {
        LocalDateTime now = ();
        LocalDateTime date1 = (2023, 7, 10, 12, 50, 10);
        Duration duration = (date1, now);
        //获取总间隔时间(秒)
        long seconds = ();
        //将间隔时间转换为 时 - 分 - 秒
        //计算间隔时间(时)
        int h = seconds > 3600 ? (int) (seconds / 3600) : 0;
        //计算间隔时间(分)
        int m = (seconds - 3600 * h) > 60 ? (int) ((seconds - 3600 * h) / 60) : 0;
        //计算间隔时间(秒)
        int s = (int) (seconds - 3600 * h - 60 * m);
        //输出测试
        (seconds);
        (h);
        (m);
        (s);
        (("yyyy-MM-dd HH:mm:ss").format(now));
        (("yyyy-MM-dd HH:mm:ss").format(date1));
    }