我已经在网上查了很多解决方案,但在解析“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);
异常(exception):
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不能只解析时间字符串吗?
最佳答案
除了Meno的答案,您需要大写的 AM
或 PM
或不区分大小写的 DateTimeFormatter
,您可以将其构建为
String startTime = "08:00 am";
DateTimeFormatter formatterTime1 = new DateTimeFormatterBuilder()
.parseCaseInsensitive().appendPattern("hh:mm a").toFormatter(Locale.US);
LocalTime localStartTime = LocalTime.parse(startTime, formatterTime1);
关于java - 使用 DateTimeFormatter "hh:mm a"解析时间导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38880271/