java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date and time work. The following code will almost give you what you asked for (only the year is only 2 digits and the clock hour only one digit). The advantage is that we’re using built-in formats and need not struggle with any format patterns ourselves — which was the part you had trouble with.
DateTimeFormatter displayFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
String fromResponse = "2020-12-31T02:00:00+05:30";
OffsetDateTime startDateTime = OffsetDateTime.parse(fromResponse);
String displayDateTimeStr = startDateTime.atZoneSameInstant(ZoneId.systemDefault())
.format(displayFormatter);
System.out.println(displayDateTimeStr);
I ran the code on my desktop Java 9 using the ThreeTen Backport library (see the link at the bottom) with default locale set to en-IN and default time zone to Asia/Kolkata. Output was:
31/12/20, 2:00 AM
If you insist on four digit year and two digit hour, specify the output format using a pattern:
DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern(
"dd/MM/uuuu, hh:mm a", Locale.forLanguageTag("en-IN"));
31/12/2020, 02:00 AM
I assumed that your user wants to see the time in his or her time zone, so I am performing a conversion using the atZoneSameInstant
method of OffsetDateTime
.
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.
What went wrong in your code?
There are two bugs in your format pattern string:
- You have got a space between
ss
and z
. In the string from the response there is no space between the seconds and the time zone offset. This caused your parsing to fail with a java.text.ParseException: Unparseable date: "2020-12-31T02:00:00+05:30"
. If you didn’t see that, you need to fix your project setup so that output from your e.printStackTrace();
is shown.
- Pattern letter
z
does not accept an offset with a colon between hours and minutes, as you’ve got in +05:30
. With the old and troublesome SimpleDateFormat
the correct pattern would have been upper case XXX
.
Links