Reputation: 241
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);
Upvotes: 0
Views: 1423
Reputation: 86378
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.
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.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 1