简体   繁体   English

从设备获取日期并将其转换为GMT + 4

[英]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 亚洲/迪拜

Question: Can I use java.time on Android? 问题:我可以在Android上使用java.time吗?

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

  • In Java 8 and later and on newer Android devices (from API level 26, I'm told) the modern API comes built-in. 在Java 8和更高版本以及更新的Android设备中(有人告诉我API级别为26),内置了现代API。
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom). 在Java 6和7中,获取ThreeTen Backport,即新类的Backport(JSR 310的ThreeTen;请参见底部的链接)。
  • On (older) Android use the Android edition of ThreeTen Backport. 在较旧的Android上,请使用Android版本的ThreeTen Backport。 It's called ThreeTenABP. 它称为ThreeTenABP。 And make sure you import the date and time classes from org.threeten.bp with subpackages. 并确保使用子包从org.threeten.bp导入日期和时间类。

Links 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM