【问题标题】:LocalDateTime parse exception with pattern "MMM, dd, yyyy, HH:mm a"LocalDateTime 解析异常,模式为“MMM,dd,yyyy,HH:mm a”
【发布时间】:2022-06-18 00:08:01
【问题描述】:

我需要帮助理解为什么以下代码会引发异常。

Exception in thread "main" java.time.format.DateTimeParseException: Text 'JUN 15, 2022, 2:24 am' could not be parsed at index 14

请注意,小时部分是用单个数字初始化的。如果添加了前导零,则第一次解析尝试成功 - 但第二个实例失败。

    String timeString = "JUN 15, 2022, 2:24 am";
    DateTimeFormatter  format = DateTimeFormatter.ofPattern("mm dd, yyyy, HH:mm a");
    format = new DateTimeFormatterBuilder().parseCaseInsensitive()
            .append(DateTimeFormatter.ofPattern("MMM dd, yyyy, HH:mm a")).toFormatter();
    LocalDateTime time = LocalDateTime.parse(timeString, format);
    System.out.println("DateTimeFormatterBuilder( ) : " + time);
    
    format = DateTimeFormatter.ofPattern("MMM dd, yyyy, HH:mm a")
            .withResolverStyle(ResolverStyle.STRICT);
    
    time = LocalDateTime.parse(timeString, format);
    System.out.println("DateTimeFormatter.ofPattern( ) : " + time);

问题:如何用 LocalDateTime 类解析单位小时的时间字符串?对于“HH:mm a”,是否需要前导零?

【问题讨论】:

  • 您是否尝试过使用单个“H”? H:mm a?
  • THX...啊...我以为 HH 会占个位数的价值。 Single H 适用于单个和 dbl 数字。但第二次尝试仍然失败 - 线程“main”中的异常 java.time.format.DateTimeParseException: Text 'JUN 15, 2022, 11:24 am' could not be parsed at index 0

标签: java localdatetime


猜你喜欢
  • 2018-05-17
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多