3

Here is my code which i am using to parse string using Instant.parse ,

String date = "2018-05-01T00:00:00";
Instant.parse(date)

And getting below error

java.time.format.DateTimeParseException: Text '2018-05-01T00:00:00' could not be parsed at index 19
        at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
        at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
        at java.time.Instant.parse(Instant.java:395)

I cannot use other then Instant so looking solution for it only!

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Wit Wikky
  • 1,542
  • 1
  • 14
  • 28
  • 1
    Which time zone is that local time supposed to be in? You can't parse to an instant without a time zone. If it's in UTC, you can simply add a "Z" to the end of the string before parsing. – Andy Turner Apr 24 '20 at 13:14
  • I am not sure about that as i am getting it from third party api response! – Wit Wikky Apr 24 '20 at 13:18
  • 1
    You should check the documentation of the third party api. – Andy Turner Apr 24 '20 at 13:28
  • `2018-05-01T00:00:00` does not define a moment in time, an instant. If you can find out what time zone or UTC offset was implied, we can help you convert to `Instant`. It seems the time of day doesn’t matter, though? So why not just parse into `LocalDate`? – Ole V.V. Apr 24 '20 at 13:41

1 Answers1

7

Instant.parse will only accept the string that are in ISO INSTANT FORMAT

Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z.

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

But the String you have represents LocalDateTime, so parse it into LocalDateTime and then convert into Instant

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime dateTime = LocalDateTime.parse(date);
Instant instant = dateTime.atZone(ZoneId.of("America/New_York")).toInstant();
Community
  • 1
  • 1
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98