为什么以下代码:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TestProject {
public static void main(String[] args) {
String dateString = "2018-03-01T14:52:48Z";
DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT;
LocalDateTime localDateTime = LocalDateTime.parse(dateString, dtf);
}
}
掷:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2018-03-01T14:52:48Z' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {NanoOfSecond=0, InstantSeconds=1519915968, MilliOfSecond=0, MicroOfSecond=0},ISO of type java.time.format.Parsed
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1959)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1894)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at org.bdshadow.TestProject.main(TestProject.java:11)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {NanoOfSecond=0, InstantSeconds=1519915968, MilliOfSecond=0, MicroOfSecond=0},ISO of type java.time.format.Parsed
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.base/java.time.format.Parsed.query(Parsed.java:235)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1890)
... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {NanoOfSecond=0, InstantSeconds=1519915968, MilliOfSecond=0, MicroOfSecond=0},ISO of type java.time.format.Parsed
at java.base/java.time.LocalDate.from(LocalDate.java:396)
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:456)
... 4 more
日期的字符串表示形式与DateTimeFormatter.ISO_INSTANT
:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT的javadoc完全相同。它在java 9中没有改变:https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT
答案 0 :(得分:4)
我相信它是因为ISO_INSTANT
用于解析Instant
正如javadoc所说:
这是一个特殊情况格式化程序,旨在允许人类可读的
java.time.Instant
形式。
此代码有效:
String dateString = "2018-03-01T14:52:48Z";
DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT;
Instant instant = Instant.from(dtf.parse(dateString));
要使其成为localdatetime,您可以使用:
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
这是对此类错误的一个很好的解释: Java SE 8 TemporalAccessor.from issues when used with a java.time.Instant object
答案 1 :(得分:1)
t contain Zone in self. If you need parse string with zone use
没有DateTimeFormatter dtf = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault());
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, dtf);
ZonedDateTime`:
{{1}}