I'm only getting this string "+0800" for a timezone from ihealth api. How can I get the corresponding java timezone id (like "US/Central") from this.
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". 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
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. ;)
Provided you use Java 8 you can use 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.
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());
}
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.