2

我已经在线检查了许多解决方案,但在解析“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);

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

4

3 回答 3

6

除了Meno的答案之外,您还需要大写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);
于 2016-08-10T17:58:15.360 回答
4

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

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

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

于 2016-08-10T17:54:02.513 回答
1

正如Meno所提到的,有两个问题

  • 您正在使用 LocalDateTime 而不是 LocalTime
  • 模式字母“a”表示您需要以大写形式指定 AM/PM,除非您使用 DateTimeFormatterBuilder 例如:

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

于 2016-08-10T17:59:38.153 回答