You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java LocalDateTime与Duration使用异常:签到逻辑不符预期求助

签到校验逻辑错误排查与修复

问题根源

你代码里的核心错误是**Duration.between的参数顺序颠倒**:
Duration.between(start, end)的规则是:如果start在end之后,返回的是负时长。当测试未来1天的预约时,Duration.between(预约时间, 当前时间)得到的是一个负的时长(比如-1440分钟),这个值和Duration.ofMinutes(10)(正10分钟)比较时,负数必然小于0,导致条件compareTo(...) < 0成立,错误触发签到成功逻辑。

修复方案

你的需求是“预约时间距离当前时间不足10分钟时允许签到”,以下两种方案可根据实际场景选择:

方案1:允许预约前后10分钟内签到(间隔绝对值≤10分钟)

LocalDateTime appointmentTime = listOfAppointment.get(Integer.parseInt(indicator) - 1).getDateTimeOfAppointment();
LocalDateTime now = LocalDateTime.now();
Duration interval = Duration.between(now, appointmentTime);

// 判断间隔的绝对值是否小于等于10分钟
if (interval.abs().compareTo(Duration.ofMinutes(10)) <= 0) {
    try {
        listOfAppointment.get(Integer.parseInt(indicator) - 1).setCheckIn(true);
        System.out.println("The check-in has been done! Let's see your PT!");
        break;
    } catch (Exception e) {
        System.out.println("Invalid input, please try again!");
        indicator = console.nextLine();
    }
} else {
    System.out.println("It seems that it's still too early, please wait until 10 minutes left!");
    break;
}

方案2:仅允许预约前10分钟内签到(预约时间在未来,且剩余时间≤10分钟)

如果需求是只能在预约快到的前10分钟签到,不允许迟到后签到,可调整条件:

LocalDateTime appointmentTime = listOfAppointment.get(Integer.parseInt(indicator) - 1).getDateTimeOfAppointment();
LocalDateTime now = LocalDateTime.now();
Duration timeUntilAppointment = Duration.between(now, appointmentTime);

// 确保预约在未来,且剩余时间≤10分钟
if (!timeUntilAppointment.isNegative() && timeUntilAppointment.compareTo(Duration.ofMinutes(10)) <= 0) {
    try {
        listOfAppointment.get(Integer.parseInt(indicator) - 1).setCheckIn(true);
        System.out.println("The check-in has been done! Let's see your PT!");
        break;
    } catch (Exception e) {
        System.out.println("Invalid input, please try again!");
        indicator = console.nextLine();
    }
} else {
    System.out.println("It seems that it's still too early, please wait until 10 minutes left!");
    break;
}

额外优化建议

  • 重复调用listOfAppointment.get(Integer.parseInt(indicator) - 1)会降低可读性,建议提前将预约对象取出赋值给变量,比如Appointment appointment = listOfAppointment.get(...);,后续直接使用appointment操作。
  • Integer.parseInt(indicator)建议添加异常捕获,避免用户输入非数字导致的NumberFormatException。

内容的提问来源于stack exchange,提问作者Qihang_W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 14:02:22