答案:通过Java的LocalDateTime和DateTimeFormatter实现任务提醒工具,支持用户输入任务时间并解析,比较当前时间后输出对应提醒信息。1. 使用Scanner接收任务名和时间字符串;2. 用DateTimeFormatter按格式解析为LocalDateTime;3. 获取当前时间并比较:若已过期则提示过期,若10分钟内开始则显示倒计时,否则显示计划时间;4. 建议添加异常处理、输入校验及多任务存储以增强健壮性。

在Java开发中,时间处理和字符串操作是日常编程中最常见的任务之一。通过实现一个简单的“任务计划提醒工具”,可以很好地练习java.time包的使用以及字符串格式化、解析等核心技能。
功能需求说明
我们要实现一个控制台程序,能够:
时间处理:LocalDateTime与DateTimeFormatter
Java 8引入的java.time包让时间操作更安全直观。我们使用LocalDateTime表示不含时区的日期时间,配合DateTimeFormatter进行字符串转换。
示例代码片段:
立即学习“Java免费学习笔记(深入)”;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入任务名称:");
String taskName = scanner.nextLine();
System.out.print("请输入提醒时间(yyyy-MM-dd HH:mm):");
String timeInput = scanner.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime reminderTime = LocalDateTime.parse(timeInput, formatter);
LocalDateTime now = LocalDateTime.now();
字符串与逻辑判断结合输出提醒
通过比较当前时间和设定时间,输出不同状态的提示。这里涉及时间差计算和字符串拼接。
判断逻辑示例:
if (reminderTime.isBefore(now)) {
System.out.println("⚠️ [" + taskName + "] 已过期!");
} else if (reminderTime.minusMinutes(10).isBefore(now)) {
System.out.println("? [" + taskName + "] 即将在" +
java.time.Duration.between(now, reminderTime).toMinutes() + "分钟内开始!");
} else {
System.out.printf("? 任务 [%s] 定于 %s 开始%n",
taskName, reminderTime.format(formatter));
}
扩展建议:增强用户体验
可进一步提升程序实用性:
- 添加输入校验,防止非法时间格式导致崩溃
- 使用
try-catch捕获DateTimeParseException - 支持重复提醒设置,用集合存储多个任务
-
格式化输出时使用
String.format或printf提升可读性










