java.time and ThreeTenABP
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"EEEE, MMM dd uuuu; hh:mm:ss a '(GMT' xxx')'", Locale.ENGLISH);
String tempDate = "Thursday, Jan 09 2020; 04:31:59 PM (GMT +05:30)";
OffsetDateTime odt = OffsetDateTime.parse(tempDate, formatter);
System.out.println(odt);
Output from this snippet is:
2020-01-09T16:31:59+05:30
In order to get the correct time you need to parse the GMT offset that is in the string.
I am using java.time, the modern Java date and time API because SimpleDateFormat
and Date
are poorly designed and long outdated, the former in particular notoriously troublesome. And because java.time is so much nicer to work with.
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.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links