Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instant.parse and RFC3339 string throws java.time.format.DateTimeParseException

If I do

import java.time.Instant;
...
    Instant instant = Instant.parse("2018-01-02T18:14:59.000+01:00")

I get this exception:

Caused by: java.time.format.DateTimeParseException: Text '2018-06-19T23:00:00.000+01:00' could not be parsed at index 23
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)

But if I do

    Instant instant = Instant.parse("2018-06-19T23:00:00.000Z");

All works fine.

What do I miss? Whats wrong with the first time string?

like image 983
badera Avatar asked Jul 11 '18 12:07

badera


2 Answers

The reason is that your first String does not match the acceptable format for parse method


As the doc states for Instant#parse(CharSequence text) :

The string must represent a valid instant in UTC and is parsed using DateTimeFormatter.ISO_INSTANT

And the doc for DateTimeFormatter#ISO_INSTANT states :

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


To get an Instant from you string you need : Workable Demo

String str = "2018-01-02T18:14:59.000+01:00";
Instant instant = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(str, Instant::from);
like image 99
azro Avatar answered Sep 28 '22 17:09

azro


Your date string contains zone information. ISO_INSTANT (default format for Instant::parse method) does not handle this. Instead use

Instant instant = DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(date, Instant::from);
like image 21
Luk Avatar answered Sep 28 '22 19:09

Luk