简体   繁体   English

从+0000格式获取Java时区ID

[英]get java Timezone id from +0000 format

I'm only getting this string "+0800" for a timezone from ihealth api. 我只从ihealth api的时区获取此字符串“ +0800”。 How can I get the corresponding java timezone id (like "US/Central") from this. 如何从中获取相应的Java时区ID(例如“ US / Central”)。

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("Z");

try {
  Date date = sdf.parse("+0800");
  cal.setTime(date);
  System.out.println(cal.getTimeZone().getID());
} catch (Exception e) {
  System.out.println("error" + e.getMessage());
}

but this always prints "Etc/UTC" which is not "+0800". 但这总是打印“ Etc / UTC”,而不是“ +0800”。 what am I missing here? 我在这里想念什么?

The difficulty in what you are asking is that there are (almost?) always many timezone names associated with a given offset. 您要问的困难是(几乎?)总是有许多与给定偏移量关联的时区名称。 So, for an offset of "+0800" we can do 因此,对于“ +0800”的偏移量,我们可以执行

int rawOffset = 8 * 3600000;  // +0800 hours converted to milliseconds
String[] tzIds = java.util.TimeZone.getAvailableIDs(rawOffset);
for (String id : tzIds) {
    System.out.println(id);
}

and see the list 并查看列表

Antarctica/Casey
Asia/Brunei
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Harbin
Asia/Hong_Kong
Asia/Kashgar
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Macao
Asia/Macau
Asia/Makassar
Asia/Manila
Asia/Shanghai
Asia/Singapore
Asia/Taipei
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Australia/Perth
Australia/West
CTT
Etc/GMT-8
Hongkong
PRC
Singapore

If you want " the corresponding java timezone id" (emphasis mine) then I guess you'll have to pick one. 如果你想“相应 Java时区ID”(重点煤矿),那么我想你必须选择一个。 ;) ;)

Provided you use Java 8 you can use ZoneOffset 如果您使用Java 8,则可以使用ZoneOffset

For example 例如

ZoneOffset zoneOffset = ZoneOffset.of("+0200");
TimeZone timezone = TimeZone.getTimeZone(zoneOffset));

Edit: ZoneOffset.of() accepts offsetId, which is different from the 4 digits representation, so this would not solve the problem. 编辑:ZoneOffset.of()接受offsetId,这与4位数字表示形式不同,所以这不能解决问题。

Try this: 尝试这个:

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("Z");

    try {
        Date date = sdf.parse("-0600");
        cal.setTime(date);
        System.out.println(sdf.format(date));
    } catch (Exception e) {
        System.out.println("error" + e.getMessage());
    }

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

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