1

Which format I should use to parse a String date (using ISO 8601) in Scala?

2018-12-13T19:19:08.266120+00:00

I just try some patterns but no success. This code show me a near date as String, but when I try with a String above, with timezone info, I get error.

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SXXX").format(new Date())

Result:

2018-12-14T17:41:24.929-02:00

Error:

java.text.ParseException: Unparseable date: "2018-12-13T19:19:08.266120+00:00" at java.text.DateFormat.parse(DateFormat.java:366) ... 29 elided

seufagner
  • 1,290
  • 2
  • 18
  • 25
  • 1
    Don’t use `SimpleDateFormat`. For one, it’s notoriously troublesome, secondly it cannot parse 6 decimals on the second (microseconds), it supports only milliseconds. Fortunately it’s also long outdated, supplanted by `DateTimeFormatter` of java.time, the modern Java date and time API. – Ole V.V. Dec 15 '18 at 09:12
  • I cannot reproduce your error. I get `Thu Dec 13 20:23:34 CET 2018`. The result is clearly incorrect, so I *would* have preferred the exception. – Ole V.V. Dec 15 '18 at 09:23

1 Answers1

5

The DateTimeFormatter class includes a number of predefined formats, including a few ISO formats. Here's one that appears to work for your example String.

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter._

val dts = "2018-12-13T19:19:08.266120+00:00"
LocalDateTime.parse(dts, ISO_DATE_TIME)
//res0: java.time.LocalDateTime = 2018-12-13T19:19:08.266120
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • 1
    Still better, use the one-arg `OffsetDateTime.parse(String)`. No need for an explicit formatter, and you will also pick up the offset from the string (in this case +00:00). – Ole V.V. Dec 15 '18 at 09:14
  • It works! Thank you so much @jwvh – seufagner Dec 15 '18 at 19:23