Java LocalDateTime 持续时间基础

Java LocalDateTime Duration fundamental

提问人:Qihang_W 提问时间:10/18/2023 最后编辑:BenjyTecQihang_W 更新时间:10/23/2023 访问量:68

问:

这是我的代码:

// check if the time within 10 mins
if (Duration.between(listOfAppointment.get(Integer.parseInt(indicator) - 1).getDateTimeOfAppointment(), LocalDateTime.now()).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 util 10 minutes left!");
    break;
}

导入了所有相关的软件包,我尝试了一天后的示例日期,但它仍然总是打印出 try-block 内容,请帮助我解决它。谢谢!

Java 持续时间

评论

2赞 Mark Rotteveel 10/18/2023
请正确格式化您的代码,并放在代码块中(即用三个反引号括起来)。您还应该打印异常堆栈跟踪并将其包含在您的问题中。永远不要忽略异常,如果你不知道是什么或为什么导致它们。
2赞 Mark Rotteveel 10/18/2023
另外,请确保您的代码是一个最小的可重现示例
0赞 Anonymous 10/18/2023
如果约会是将来的,你不应该把参数换成?这样:?(你也可以检查你的假设,即它是在未来,这样你就不会碰巧检查昨天应该在这里的人。between()Duration.between(LocalDateTime.now(), listOfAppointment.get(Integer.parseInt(indicator) - 1).getDateTimeOfAppointment())
1赞 Qihang_W 10/20/2023
是的,这就是问题所在。已经更新了我的代码,谢谢!

答:

1赞 Pablo Aragonés 10/18/2023 #1

您似乎正在尝试检查约会时间是否在当前时间的 10 分钟内,如果是,请将签到标志设置为 ,不是吗?但是,您的代码中存在问题。您不必要地使用了块并破坏了块内的循环。以下是我认为是您的代码的更正版本:truetry-catchtry

// Assuming you have already parsed the indicator as an integer
int index = Integer.parseInt(indicator) - 1;
LocalDateTime appointmentTime = listOfAppointment.get(index).getDateTimeOfAppointment();
LocalDateTime now = LocalDateTime.now();
Duration timeDifference = Duration.between(appointmentTime, now);

if (timeDifference.compareTo(Duration.ofMinutes(10)) < 0) {
    listOfAppointment.get(index).setCheckIn(true);
    System.out.println("The check-in has been done! Let's see your PT!");
} else {
    System.out.println("It seems that it's still too early, please wait until 10 minutes are left!");
}
0赞 Qihang_W 10/23/2023 #2

更新的答案 - 应交换 appointmentTime 和 now 变量的索引,如下所示:

int index = Integer.parseInt(indicator) - 1;

LocalDateTime appointmentTime = listOfAppointment.get(index).getDateTimeOfAppointment();

LocalDateTime now = LocalDateTime.now();

Duration timeDifference = Duration.between(now, appointmentTime);

if (timeDifference.compareTo(Duration.ofMinutes(10)) < 0) {

    listOfAppointment.get(index).setCheckIn(true);
    System.out.println("The check-in has been done! Let's see your PT!");
} 

else {
    
System.out.println("It seems that it's still too early, please wait until 10 minutes are left!");

}