I get time with time zone (without date component) from a PostgreSQL server in json like this { "time": "03:00:00+01" }
. How do I handle this in Android? Is there any structure which can hold just time without date? Or converting it to the epoch Date
representation i.e. Thu Jan 01 03:00:00 GMT+01:00 1970
is the only good solution?
OffsetTime from java.time and ThreeTenABP
An OffsetTime
is a time of day without date and with an offset from UTC. It thus very precisely models the information in your string from JSON. So I would clearly prefer it over Date
. Also because the Date
class is poorly designed and long outdated.
String timeStringFromJson = "03:00:00+01";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ssX");
OffsetTime parsedTime = OffsetTime.parse(timeStringFromJson, timeFormatter);
System.out.println("Parsed time: " + parsedTime);
Output from this snippet is:
Parsed time: 03:00+01:00
As a detail that may or may not matter to you, the offset from the string is retained, contrary to what Date
can do because a Date
hasn’t got a time zone or offset.
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 use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.