Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing ISO_INSTANT and similar Date Time Strings

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

like image 692
ycomp Avatar asked Sep 28 '15 14:09

ycomp


People also ask

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What is iso_instant?

ISO_INSTANT. The ISO instant formatter that formats or parses an instant in UTC, such as '2011-12-03T10:15:30Z'.

What is the Java time format DateTimeFormatter?

format. DateTimeFormatterBuilder Class in Java. DateTimeFormatterBuilder Class is a builder class that is used to create date-time formatters. DateTimeFormatter is used as a Formatter for printing and parsing date-time objects.

Is Java time format DateTimeFormatter thread-safe?

DateTimeFormatter is immutable and thread-safe. DateTimeFormatter formats a date-time using user defined format such as "yyyy-MMM-dd hh:mm:ss" or using predefined constants such as ISO_LOCAL_DATE_TIME. A DateTimeFormatter can be created with desired Locale, Chronology, ZoneId, and DecimalStyle.


1 Answers

Just for the sake of helping anyone seeing this question later.

You need to parse the ISO Date as Instant, convert it to Instant Object and then create a LocalDateTime from it providing the zone Id. I'm setting the zone Id of UTC 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;
}
like image 149
Ahmed Kamal Avatar answered Oct 13 '22 18:10

Ahmed Kamal