【发布时间】:2021-05-28 05:45:18
【问题描述】:
当我运行它时,我得到了异常: 线程“主”java.time.format.DateTimeParseException 中的异常:无法解析文本“2020-12-15 13:48:52”:ClockHourOfAmPm 的值无效(有效值
我写信给控制台:2020-12-15 13:48:52
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Podaj datę:");
String input = scanner.nextLine();
if (input.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(input, dateTimeFormatter1);
printDateTime(localDateTime);
} else if (input.matches("\\d{2}.\\d{2}.\\d{4} \\d{2}:\\d{2}:\\d{2}")) {
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm:ss");
LocalDateTime localDateTime2 = LocalDateTime.parse(input, dateTimeFormatter2);
printDateTime(localDateTime2);
} else if (input.matches("\\d{4}-\\d{2}-\\d{2}")) {
DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime localDateTime3 = LocalDateTime.parse(input, dateTimeFormatter3);
printDateTime(localDateTime3);
} else {
System.out.println("Zły format");
}
}
private static void printDateTime(LocalDateTime localDateTime) {
System.out.println("Czas lokalny: " + ZonedDateTime.now());
System.out.println("UTC: " + ZonedDateTime.of(localDateTime, ZoneId.of("UTC")));
System.out.println("Londyn: " + ZonedDateTime.of(localDateTime, ZoneId.of("London")));
System.out.println("Los Angeles: " + ZonedDateTime.of(localDateTime, ZoneId.of("Los Angeles")));
System.out.println("Sydney: " + ZonedDateTime.of(localDateTime, ZoneId.of("Sydney")));
}
}
【问题讨论】:
-
使用 HH 代替 hh。此外,伦敦不是有效的 ZondId
-
或者:
LocalDateTime.parse( "2020-12-15 13:48:52".replace( " " , "T" ) )将中间的空格替换为T,以符合 java.time 中默认使用的标准 ISO 8601 格式。
标签: java datetime java-time zoneddatetime datetimeformatter