[英]Get date from device and convert it to GMT+4
I am trying to find the timezone of the android phone. 我正在尝试查找android手机的时区。 Because I want to get the date object but I want in GMT+4 format.
因为我想获取日期对象,但我想使用GMT + 4格式。 Every other answer I saw converts the time coming from an API request(whose timezone is known).
我看到的所有其他答案都将转换来自API请求的时间(已知时区)。 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. 其他方法可能是将来自我的GMT + 4时间从服务器转换为设备的本地时间。
Best to use a real time zone rather than just an offset of +04. 最好使用实时区域,而不仅仅是偏移+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
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)
. 如果您确实坚持使用GMT + 4,请使用
ZoneOffset.ofHours(4)
。
The old Date
class cannot hold an offset or time zone, but the modern OffsetDateTime
does, as the name says. OffsetDateTime
,旧的Date
类不能包含偏移量或时区,而现代的OffsetDateTime
可以。 The Date
class is also poorly designed, so do consider using java.time, the modern Java date and time API. Date
类的设计也很差,因此请考虑使用java.time(现代Java日期和时间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. 是的,
java.time
在较新和较旧的Android设备上java.time
正常运行。 It just requires at least Java 6 . 它至少需要Java 6 。
org.threeten.bp
with subpackages. org.threeten.bp
导入日期和时间类。 java.time
. java.time
。 java.time
was first described. java.time
。 java.time
to Java 6 and 7 (ThreeTen for JSR-310). java.time
到Java 6和7的java.time
移植(JSR-310的ThreeTen)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.