I am trying to parse various slightly different date strings for an Android application.
Two examples are:
Thu, 20 Aug 2020 13:30:16 +0000
Wed, 19 Aug 2020 15:28:47 GMT
Here is how I tried parsing these Strings:
Date pubDate = org.apache.commons.lang3.time.DateUtils.parseDate(dateString,
"EEE, dd MMM yyyy HH:mm:ss Z", "EEE, dd MMM yyyy HH:mm:ss zzz");
As far as I can tell this should work, but I am getting java.text.ParseException: Unable to parse the date: Wed, 19 Aug 2020 15:28:47 GMT exceptions for both those examples. What am I doing wrong here?
Your format is built into java.time
Use
DateTimeFormatter.RFC_1123_DATE_TIME; it works for both of your strings. It’s really the same format, only with the offset from UTC (or GMT) denoted differently.DateTimeFormatteris part of java.time, the modern Java date and time API. I recommend that you prefer java.time overDateandDateUtils, also because theDateclass is poorly designed and long outdated.Output is:
Let’s try with your other string example:
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bpwith subpackages.Links
java.timewas first described.java.timeto Java 6 and 7 (ThreeTen for JSR-310).