0

I have a problem with creating date and I don't know what I do wrong... Below is a code snippet:

val time = "2021-08-25 12:13:33"
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val instant = ZonedDateTime.parse(time, format).toInstant
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)

Errors:

java.time.format.DateTimeParseException: Text '2021-08-25 12:13:33' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2021-08-25T12:13:33 of type java.time.format.Parsed
  at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
  at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
  at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:598)
  ... 40 elided
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2021-08-25T12:13:33 of type java.time.format.Parsed
  at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:566)
  at java.base/java.time.format.Parsed.query(Parsed.java:235)
  at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
  ... 41 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: {},ISO resolved to 2021-08-25T12:13:33 of type java.time.format.Parsed
  at java.base/java.time.ZoneId.from(ZoneId.java:463)
  at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:554)
  ... 43 more

I have no idea what is going on...

Izmo
  • 25
  • 5
  • 3
    You are trying to parse your String as a `ZonedDateTime`, but your pattern does not provide zone information. Try parsing it to a `LocalDateTime` instead. – Hulk Sep 10 '21 at 12:22
  • ```val time = "2021-08-25 12:13:33" val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val instant = LocalDateTime.parse(time, format).toInstant(ZoneOffset.UTC).toEpochMilli``` works :) Thanks @Hulk! – Izmo Sep 10 '21 at 12:35
  • 2
    @hulk I believe that what OP wants is to parse the datetime as it was in UTC, so using `LocalDateTime` would produce erroneous values, in that case Izumo you can do [this](https://scastie.scala-lang.org/BalmungSan/3zHQGThaS6KcMcGaDBSlow); let me know if that is what you want so I can add a proper answer. – Luis Miguel Mejía Suárez Sep 10 '21 at 12:37
  • Yeah, my aim was obtain ZonedDateTime, Luis your answer is correct. Thanks for both of you guys! – Izmo Sep 10 '21 at 12:52

0 Answers0