Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I created this wonderful static method yesterday, and it worked just fine - yesterday

However, today it gives me this error. I guess it is from too many 0s before the Z.

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

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));
}

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
408 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

Note that this formatter handles correctly fractional seconds so you don't need to remove them. Quoting DateTimeFormatter.ISO_INSTANT Javadoc (emphasis mine):

When parsing, time to at least the seconds field is required. Fractional seconds from zero to nine are parsed.

As to why it worked yesterday and not today, I have no idea...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...