java.time either through desugaring or ThreeTenABP
Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first define the formatters we need:
private static final DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX");
private static final DateTimeFormatter outputFormatter
= DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
( DateTimeFormatter
is thread-safe, so we can safely declare them static.) Do the time zone conversion explicitly:
String startString = "20201023T200457Z";
Instant start = inputFormatter.parse(startString, Instant.FROM);
String target = start.atZone(ZoneId.systemDefault()).format(outputFormatter);
System.out.println(target);
Output in my time zone (currently at offset +02:00 like yours):
20201023 22:04:57
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. Only in this case use the method reference
Instant::from
instead of the constant Instant.FROM
.
- 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 either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links