我正在尝试使用扫描仪将字符串 (11:23) 解析为 LocalDateTime,但出现异常: 无法解析文本“11:23”:无法从 TemporalAccessor 获取 LocalDateTime:{},ISO 解析为 java.time.format.Parsed 类型的 11:23
Scanner scanner = new Scanner(System.in);
String timeGivenByUserString;
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
System.out.println("Type the time HH:mm");
try {
do {
timeGivenByUserString = scanner.nextLine();
} while (!timeGivenByUserString.matches("\\d{2}:\\d{2}"));
LocalDateTime timeGivenByUser = LocalDateTime.parse(timeGivenByUserString, timeFormatter);
System.out.println(timeGivenByUser.format(timeFormatter));
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
}
我也创建了类似的方法,它工作得很好:
private static void askAboutDate() {
Scanner scanner = new Scanner(System.in);
String dateGivenByUserString;
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
System.out.println("Type the date dd.MM.yyyy");
try {
do {
dateGivenByUserString = scanner.nextLine();
} while (!dateGivenByUserString.matches("\\d{2}.\\d{2}.\\d{4}"));
LocalDate dateGivenByUser = LocalDate.parse(dateGivenByUserString, dateFormatter);
System.out.println(dateGivenByUser.format(dateFormatter));
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
}
}
最佳答案
解决方案: 将 LocalDateTime 更改为 LocalTime
Scanner scanner = new Scanner(System.in);
String timeGivenByUserString;
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
System.out.println("Type the time HH:mm");
try {
do {
timeGivenByUserString = scanner.nextLine();
} while (!timeGivenByUserString.matches("\\d{2}:\\d{2}"));
LocalTime timeGivenByUser = LocalTime.parse(timeGivenByUserString, timeFormatter);
System.out.println(timeGivenByUser.format(timeFormatter));
} catch (DateTimeParseException e) {
System.out.println(e.getMessage());
}
关于java - 如何从字符串中解析时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599245/