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

如何将系统当前LocalDateTime与输入的日期时间字符串进行比较

实现逻辑

  • 先将用户输入的字符串用你定义的DateTimeFormatter解析为LocalDateTime对象,需捕获格式不匹配的异常
  • 调用LocalDateTime自带的isBefore()、isEqual()方法完成时间比较
  • 注意:你当前定义的静态time变量存储的是类加载时的时间,不是判断逻辑执行时的实时时间,建议判断时直接调用LocalDateTime.now()获取当前时间,若确实需要以程序启动时间为对比基准可保留原有静态变量

修改后的完整代码如下:

import java.time.format.DateTimeParseException;

// 你原有定义的 formatter 保持不变
static DateTimeFormatter frmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");

// 输入和判断逻辑
System.out.print("Enter the Appointment new Date and Time as dd-MM-yyyy HH:mm : ");
String dateAndTime = input.nextLine();
LocalDateTime inputTime;

// 解析输入的日期时间
try {
    inputTime = LocalDateTime.parse(dateAndTime, frmt);
} catch (DateTimeParseException e) {
    System.out.println("输入的日期格式不合法,请按照 dd-MM-yyyy HH:mm 格式输入");
    // 此处可根据业务需求添加重试、退出等逻辑
    return;
}

// 时间比较判断
if (inputTime.isBefore(LocalDateTime.now()) || inputTime.isEqual(LocalDateTime.now())) {
    System.out.println("The new date and time should be after the current time");
} else {
    System.out.println("Appointment has been updated");
}

额外注意点

你原有输入提示里的dd-mm-yyyy hh:mm写法有误:mm对应分钟,MM才对应月份,hh是12小时制,HH是24小时制,和你定义的formatter规则不一致,建议修改输入提示避免用户输入错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:54:03