How does GMT IDs work in Java TimeZone?

一笑奈何 提交于 2021-01-28 13:18:44

问题


I'm currently working with different time zones, using java.util.TimeZone. First thing I did was to get a list of TimeZone IDs, using TimeZone.getAvailableIDs();

It returned a bunch of Etc/GMT IDs, such as

Etc/GMT
Etc/GMT+0
Etc/GMT+1

The Javadoc for TimeZone says to use "For example, GMT+10 and GMT+0010"

To make sure I was using the correct one, I made a small test with both IDs, and the results didn't match what I was expecting:

String id = "GMT-1";
Calendar c = Calendar.getInstance(TimeZone.getTimeZone(id));
System.out.println(id + '\n' + c.getTimeZone().getDisplayName() + " HOUR_OF_DAY " + c.get(Calendar.HOUR_OF_DAY) + '\n');

id = "GMT+1";
c = Calendar.getInstance(TimeZone.getTimeZone(id));
System.out.println(id + '\n' + c.getTimeZone().getDisplayName() + " HOUR_OF_DAY " + c.get(Calendar.HOUR_OF_DAY) + '\n');

id = "Etc/GMT-1";
c = Calendar.getInstance(TimeZone.getTimeZone(id));
System.out.println(id + '\n' + c.getTimeZone().getDisplayName() + " HOUR_OF_DAY " + c.get(Calendar.HOUR_OF_DAY) + '\n');

id = "Etc/GMT+1";
c = Calendar.getInstance(TimeZone.getTimeZone(id));
System.out.println(id + '\n' + c.getTimeZone().getDisplayName() + " HOUR_OF_DAY " + c.get(Calendar.HOUR_OF_DAY) + '\n');

Shows me the output

GMT-1
GMT-01:00 HOUR_OF_DAY 18

GMT+1
GMT+01:00 HOUR_OF_DAY 20

Etc/GMT-1
GMT+01:00 HOUR_OF_DAY 20

Etc/GMT+1
GMT-01:00 HOUR_OF_DAY 18

So my question is: What are these Etc/GMT IDs for? Why would they give me -X when I used +X and vice versa?


回答1:


The Etc/GMT... time zones are there primarily for backwards compatibility with POSIX standards, which specified positive offsets west of GMT instead of the typical convention east of GMT that you might be used to.

In most cases, you should not use them. For example, if you are in the US Pacific time zone, you should use the identifier America/Los_Angeles. It alternates between UTC-8 for standard time in the winter, and UTC-7 for daylight time in the summer. You shouldn't just use Etc/GMT+8, because that wouldn't account for daylight saving time.

Other than backwards compatibility, another area where these fixed-offset zones come into play is for nautical purposes. Ships at sea have a lot of control over how they set their time, but they typically use fixed offsets separated by 15 degrees of longitude. It would be perfectly acceptable for a ship in the Atlantic ocean to use a time zone setting identifier of Etc/GMT+3.

Just don't forget to invert the sign. Etc/GMT+3 = UTC-3

Additional reading:

  • The comments in the etcetera file of the IANA/Olson time zone data
  • The timezone tag wiki
  • Wikipedia article on Nautical Time


来源:https://stackoverflow.com/questions/23640227/how-does-gmt-ids-work-in-java-timezone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!