解析ISO_INSTANT和类似的日期时间字符串 [英] Parsing ISO_INSTANT and similar Date Time Strings
问题描述
昨天我创建了这个精彩的静态方法,它工作得很好 - 昨天
I created this wonderful static method yesterday, and it worked just fine - yesterday
然而,今天它给了我这个错误。我猜它是Z之前的太多0。
However, today it gives me this error. I guess it is from too many 0s before the Z.
任何人都可以推荐如何以简洁的方式解析(Java 8)这种类型的字符串
格式日期 - 请记住它昨天也有效,所以 ISO_INSTANT
也是 String <的有效格式/ code>?
Can anyone recommend how to parse in a concise way (Java 8) this type of String
format date - keeping in mind that it worked yesterday too, so ISO_INSTANT
is also a valid format for the String
?
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {NanoOfSecond=0, InstantSeconds=1443451604, MilliOfSecond=0, MicroOfSecond=0},ISO of type java.time.format.Parsed
at java.time.LocalDate.from(LocalDate.java:368)
at java.time.LocalDateTime.from(LocalDateTime.java:456)
... 9 more
在输入时间抛出异常:2015-09-28T14:46:44.000000Z
throwing an exception on input time: "2015-09-28T14:46:44.000000Z"
/**
*
* @param time the time in RFC3339 format (e.g. "2013-07-03T14:30:38Z" )
* @return
*/
public static LocalDateTime parseTimeINSTANT(String time) {
DateTimeFormatter f = DateTimeFormatter.ISO_INSTANT;
return LocalDateTime.from(f.parse(time));
}
推荐答案
您正在解析与ISO即时一致的字符串,因此您需要将结果存储在 Instant
而不是 LocalDateTime
:
You are parsing a String that is consistent with an ISO instant so you need to store the result in a Instant
instead of LocalDateTime
:
public static Instant parseTimeINSTANT(String time) {
DateTimeFormatter f = DateTimeFormatter.ISO_INSTANT;
return Instant.from(f.parse(time)); // could be written f.parse(time, Instant::from);
}
请注意,此格式化程序正确处理小数秒,因此您无需删除他们。引用 DateTimeFormatter。 ISO_INSTANT
Javadoc(强调我的):
Note that this formatter handles correctly fractional seconds so you don't need to remove them. Quoting DateTimeFormatter.ISO_INSTANT
Javadoc (emphasis mine):
解析时,至少到秒字段的时间是必须的。 从0到9的小数秒被解析。
至于为什么它在昨天而不是今天工作,我不知道......
As to why it worked yesterday and not today, I have no idea...
这篇关于解析ISO_INSTANT和类似的日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!