提问人:Qihang_W 提问时间:10/18/2023 最后编辑:BenjyTecQihang_W 更新时间:10/23/2023 访问量:68
Java LocalDateTime 持续时间基础
Java LocalDateTime Duration fundamental
问:
这是我的代码:
// 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 内容,请帮助我解决它。谢谢!
答:
1赞
Pablo Aragonés
10/18/2023
#1
您似乎正在尝试检查约会时间是否在当前时间的 10 分钟内,如果是,请将签到标志设置为 ,不是吗?但是,您的代码中存在问题。您不必要地使用了块并破坏了块内的循环。以下是我认为是您的代码的更正版本:true
try-catch
try
// 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!");
}
评论
between()
Duration.between(LocalDateTime.now(), listOfAppointment.get(Integer.parseInt(indicator) - 1).getDateTimeOfAppointment())