I am getting UTC time from the server in 2021-06-20T09:56:05.697Z format. I want to format it to user time zone and I tried the below code. But it returns
java.text.ParseException: Unparseable date: "2021-06-20T09:56:05.697Z"
Code used : (dateInString from server as "2021-06-20T09:56:05.697Z")
String dateStr = dateInString;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateex = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(dateex);
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:
Now the conversion goes like this:
Example output:
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.
org.threeten.bpwith subpackages.Links
java.timewas first described.java.timeto Java 6 and 7 (ThreeTen for JSR-310).