使用 DateTimeFormatter "hh:mm a" 解析时间导致异常

Parsing time with DateTimeFormatter "hh:mm a" cause Exception

我已经在网上查了很多解决方案,但在解析时仍然出现异常"hh:mm a"。

在JSP中:

$('#t2').timepicker({
                        timeFormat : 'hh:mm a',
                        interval : 30,
                        maxTime : '11:00 pm',
                        startTime : '08:00 am',
                        dynamic : false,
                        dropdown : true,
                        scrollbar : true
                    });

...

                                    <div class="form-group">
                                        <label
                                            class="col-md-3 control-label">Start
                                            Time</label>
                                        <div class="col-md-7">
                                            <input type="text"
                                                class="timepicker"
                                                id="t1"
                                                name="startTime"
                                                readonly="readonly">
                                        </div>
                                    </div>

在Java中:

String startTime = request.getParameter("startTime");
DateTimeFormatter formatterTime1 = DateTimeFormatter.ofPattern("hh:mm a", Locale.US);
LocalDateTime localStartTime = LocalDateTime.parse(startTime, formatterTime1);

异常:

java.time.format.DateTimeParseException: Text '08:00 am' could not be parsed at index 6

即使我尝试硬编码:

String startTime = "08:00 am" (08:00am, 8:00am);

同样的问题。 即使在单个测试文件中。 是因为Java8不能只解析时间字符串吗?

您可以将 "hh:mm a" 解析为 LocalTime 但不能解析为 LocalDateTime,因为没有日期信息。为什么解析器要疯狂地为您猜测任意日期?我的建议是选择日期:

LocalTime localStartTime = LocalTime.parse(startTime, formatterTime1);
LocalDateTime ldt = LocalDate.of(...).atTime(localStartTime);

相比之下,旧SimpleDateFormat使用默认日期1970-01-01,即UNIX纪元的日期。但我不认为这是旧 API 的合理设计决策,只是通过解析为 java.util.Date 的即时类实例(由于缺少时间类型 LocalTime).

除了 的答案外,您还需要大写 AMPM 或不区分大小写的 DateTimeFormatter,您可以将其构建为

String startTime = "08:00 am";
DateTimeFormatter formatterTime1 = new DateTimeFormatterBuilder()
   .parseCaseInsensitive().appendPattern("hh:mm a").toFormatter(Locale.US);
LocalTime localStartTime = LocalTime.parse(startTime, formatterTime1);

Meno提到的有两个问题

  • 您使用的是 LocalDateTime 而不是 LocalTime
  • pattern letter 'a' 意味着你需要指定 AM/PM 大写,除非你使用 DateTimeFormatterBuilder ex:

    LocalTime localStartTime = LocalTime.parse("08:00 AM", formatterTime1);