I am trying to find the timezone of the android phone. Because I want to get the date object but I want in GMT+4 format. Every other answer I saw converts the time coming from an API request(whose timezone is known). How can I accomplish this?
Other approach may be converting the GMT+4 time that comes to me from server to the local time of my device.
Best to use a real time zone rather than just an offset of +04. For example:
OffsetDateTime currentDateTimeInGeorgia = OffsetDateTime.now(ZoneId.of("Asia/Tbilisi"));
System.out.println(currentDateTimeInGeorgia);
This snippet just output:
2018-09-13T19:18:35.642592+04:00
Please substitute your own time zone. If you do insist on GMT+4, use ZoneOffset.ofHours(4)
.
The old Date
class cannot hold an offset or time zone, but the modern OffsetDateTime
does, as the name says. The Date
class is also poorly designed, so do consider using java.time, the modern Java date and time API.
As you see, the above doesn't use the device time zone. If you need this anyway:
ZoneId deviceTimeZone = ZoneId.systemDefault();
System.out.println(deviceTimeZone);
Example output:
Asia/Dubai
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6 .
org.threeten.bp
with subpackages. java.time
. java.time
was first described. java.time
to Java 6 and 7 (ThreeTen for JSR-310).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.