要判断一个 LocalDateTime 对象与当前时间是否相差半小时,可以使用以下步骤:

  1. 获取当前时间的 LocalDateTime 对象。可以使用 LocalDateTime.now() 方法获取当前时间的 LocalDateTime 对象。

  2. 计算两个 LocalDateTime 对象之间的时间差。可以使用 Duration.between() 方法计算两个时间点之间的时间差。

  3. 判断时间差是否大于等于 30 分钟。可以使用 toMinutes() 方法将时间差转换为分钟,并判断是否大于等于 30。

下面是一个示例代码:

import java.time.Duration;
import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        // 获取当前时间的 LocalDateTime 对象
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 创建一个 LocalDateTime 对象,表示要比较的时间
        LocalDateTime targetDateTime = LocalDateTime.of(2022, 1, 1, 12, 0, 0);

        // 计算两个 LocalDateTime 对象之间的时间差
        Duration duration = Duration.between(currentDateTime, targetDateTime);

        // 判断时间差是否大于等于 30 分钟
        if (duration.toMinutes() >= 30) {
            System.out.println('两个时间相差半小时或更多。');
        } else {
            System.out.println('两个时间相差少于半小时。');
        }
    }
}

在上面的示例中,我们比较了当前时间和 2022 年 1 月 1 日 12:00:00 之间的时间差,并判断时间差是否大于等于 30 分钟。根据实际情况,你可以替换 targetDateTime 的值为你想要比较的时间。

Java LocalDateTime 时间差判断: 如何判断两个时间是否相差半小时

原文地址: https://www.cveoy.top/t/topic/4RV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录