尝试解析LocalDateTime时发生异常 [英] Exception when trying to parse a LocalDateTime
问题描述
我正在使用以下时间戳格式:
I am using the following timestamp format:
yyyyMMddHHmmssSSS
以下方法可以正常工作:
The following method works fine:
public static String formatTimestamp(final Timestamp timestamp, final String format) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return timestamp.toLocalDateTime().format(formatter);
}
而且,当我传入带有该格式字符串的时间戳时,它返回,例如:
And, when I pass in a Timestamp with that format string, it returns, for example:
20170925142051591
然后我需要再次从该字符串映射到时间戳,本质上是相反的操作.我知道我可以使用SimpleDateFormat
及其parse()
方法,但是如果可能的话,我宁愿坚持使用java.time
样式格式.
I then require to map from that string to a Timestamp again, essentially the reverse operation. I know that I can use a SimpleDateFormat
and its parse()
method, but I'd prefer to stick to java.time
style formatting, if possible.
我写了这段(有点怪异)的代码,它适用于某些格式,但不适用于这种特定格式:
I wrote this (rather hacky) bit of code, which works with some formats, but not with this particular one:
public static Timestamp getTimestamp(final String text, final String format, final boolean includeTime) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
final TemporalAccessor temporalAccessor = formatter.parse(text);
if (includeTime) {
final LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
return DateTimeUtil.getTimestamp(localDateTime);
} else {
final LocalDate localDate = LocalDate.from(temporalAccessor);
return DateTimeUtil.getTimestamp(localDate);
}
}
在第二行的formatter.parse(text);
部分失败.
堆栈跟踪:
java.time.format.DateTimeParseException: Text '20170925142051591' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at java.time.LocalDateTime.parse(LocalDateTime.java:477)
at com.csa.core.DateTimeUtil.main(DateTimeUtil.java:169)
是否有一种更简单的方法可以在不利用SimpleDateFormat
的情况下实现我想要的?
Is there a simpler way to achieve what I want without utilising SimpleDateFormat
?
推荐答案
是一个错误: https://bugs.openjdk.java.net/browse/JDK-8031085
上面的链接还提供了解决方法:将java.time.format.DateTimeFormatterBuilder
与java.time.temporal.ChronoField
一起用于毫秒字段:
The link above also provides the workaround: using a java.time.format.DateTimeFormatterBuilder
with a java.time.temporal.ChronoField
for the milliseconds field:
String text = "20170925142051591";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// date/time
.appendPattern("yyyyMMddHHmmss")
// milliseconds
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
// create formatter
.toFormatter();
// now it works
formatter.parse(text);
不幸的是,似乎没有办法仅使用DateTimeFormatter.ofPattern(String)
来解析它.
Unfortunately, there seems to be no way to parse this using only DateTimeFormatter.ofPattern(String)
.
这篇关于尝试解析LocalDateTime时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!