Parsing ISO_INSTANT and similar time strings

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

However, today it gives me this error. I think this is because the number 0 to Z is too large.

Can anyone recommend parsing (Java 8) of this type of String format date - given that it worked yesterday, so is ISO_INSTANT also a valid format for 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 

throw exception during input: "2015-09-28T14: 46: 44.000000Z"

 /** * * @param time the time in RFC3339 format (eg "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

+6
source share
2 answers

You are LocalDateTime ISO compliant string, so you need to save the result in 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); } 

Please note that this formatter handles fractional seconds correctly, so you do not need to delete them. Quoting DateTimeFormatter.ISO_INSTANT Javadoc (focus):

When parsing, it takes time at least for a field of seconds. Fractional seconds are developed from zero to nine.

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

+11
source

Just to help someone see this question later.

You need to LocalDateTime ISO date as Instant , convert it to an Instant Object, and then create a LocalDateTime from it, providing the zone identifier. I set the UTC zone identifier here.

The code is as follows

 public static LocalDateTime getISODate(String dateString) { DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_INSTANT; Instant dateInstant = Instant.from(isoFormatter.parse(dateString)); LocalDateTime date = LocalDateTime.ofInstant(dateInstant, ZoneId.of(ZoneOffset.UTC.getId())); return date; } 
+3
source

All Articles