java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first declare a formatter for the format we want:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z", Locale.ENGLISH);
Now the conversion goes like this:
String dateStr = "2021-06-20T09:56:05.697Z";
Instant dateex = Instant.parse(dateStr);
ZonedDateTime dateTime = dateex.atZone(ZoneId.systemDefault());
String formattedDate = dateTime.format(FORMATTER);
System.out.println("Formatted date and time: " + formattedDate);
Example output:
Formatted date and time: 2021-06-20 05:56:05 AST
This was running on a computer in America/Tortola time zone, and we see that the date and time have been converted to Atlantic Standard Time as requested.
I am exploiting the fact that the string from the server is in ISO 8601 format, a format that the classes of java.time generally parse natively without any explicit formatter.
What went wrong in your code?
When parsing the string from the server, if using a formatter for it, that formatter needs to know the format to be parsed. It doesn’t help that it knows the format to be formatted into later.
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 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