0

Maybe it's little stupid question, but I lost some hours on it now and could be great if someone will find a time to share his experience.

I'm trying to parse the date from string: 2018-05-01 13:54:46 CEST

To parse this date I'm using following pattern: yyyy-MM-dd HH:mm:ss z

And code:

private fun dateFromStringUsingPattern(dateString : String, formatPattern : String) : Date? {
        val simpleDateFormat = SimpleDateFormat(formatPattern, Locale.US)

        try {
            return simpleDateFormat.parse(dateString)
        } catch (e : Exception) {
            e.printStackTrace()
        }

        return null
    }

But unfortunately I have exception java.text.ParseException: Unparseable date: "2018-05-01 13:54:46 CEST"

I also tested my pattern there http://www.sdfonlinetester.info/ and it seems to be ok.

What could be wrong?

Thanks

Andrey
  • 2,659
  • 4
  • 29
  • 54
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. May 01 '18 at 12:10
  • 1
    I cannot reproduce. It parses nicely on my Java 9. On my Java 7 too. One possible explanation is if your string contains “funny” characters, for example a non-printable character somewhere or a non-breaking space instead of a normal space. – Ole V.V. May 01 '18 at 12:13
  • Unfortunately I'm unable to use DateTimeFormatter, because it's appeared only in Android 26, and my code is for Android 21 :( – Andrey May 01 '18 at 12:16
  • No big problem, Andrey. `java.time` has been backported. The Android edition of the backport is called ThreeTenABP, and there’s a thorough guide [in this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. May 01 '18 at 12:18
  • 2
    I disagree in the close votes. This question has a clear problem statement and code to reproduce. As long as the asker can reproduce, you can’t say it can no longer be reproduced. It’s a difficult question to answer for those of us who can’t reproduce, but that doesn’t invalidate the question. – Ole V.V. May 01 '18 at 12:24
  • Agreed. In both cases – Deividi Cavarzan May 01 '18 at 12:31
  • 1
    If you try parsing a string like `"2018-05-01\u00A013:54:46 CEST"` or `"\u00002018-05-01 13:54:46 CEST"`, you will get an exception that looks exactly like the one you’re quoting, for example. – Ole V.V. May 01 '18 at 12:33

0 Answers0