1

I am trying to parse a string of the format "Thu May 07 00:00:00 CEST 2020" to a java.util.Date. I use the suggested approaches with SimpleDateFormat. However, all the formats I've tried lead to "java.text.ParseException: Unparseable date".

My code looks like this:

fun String.toDate(format: String = "EEE MMM dd HH:mm:ss z yyyy"): Date = SimpleDateFormat(format).parse(this)

I've tried formats such as

  • "EEE MMM dd HH:mm:ss z yyyy"
  • "EEE MMM dd HH:mm:ss zzzz yyyy"
  • "EEE MMM d HH:mm:ss z yyyy"
  • "EEE MMM d HH:mm:ss zzzz yyyy"

All of them lead to the same exception. What am I missing?

Heiko
  • 149
  • 1
  • 9
  • Hello Heiko, please take a detailed look at the Patterns: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html – Martin Marconcini May 08 '20 at 09:23
  • 1
    I used your first pattern and it parses fine; here's the Kotlin Playground with the 3 lines of parsing code: https://pl.kotl.in/83YxoQpic – Martin Marconcini May 08 '20 at 09:39
  • Does this answer your question? [Java - Unparseable date](https://stackoverflow.com/questions/6154772/java-unparseable-date) Or this? [Getting error java.text.ParseException: Unparseable date: (at offset 0) even if the Simple date format and string value are identical](https://stackoverflow.com/questions/46285384/getting-error-java-text-parseexception-unparseable-date-at-offset-0-even-if) – Ole V.V. May 10 '20 at 19:15
  • 3
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 10 '20 at 19:16

2 Answers2

0

I had the same issue. The first pattern that you have written is correct. I used LocalDateTime.

LocalDateTime.parse("Thu May 07 00:00:00 CEST 2020", DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy")

To convert this to Date type, use Date.from(localDatetimeObj.atZone(ZoneId.of(zoneId)).toInstant())

with zoneId eg "UTC"

Leena
  • 703
  • 1
  • 12
  • 21
0

Might be some issue with your localization. Try putting Locale.ENGLISH in the definition of the format.