Get Military Time Zone Abbreviation

2019-06-14 22:37发布

问题:

I have a org.joda.time.DateTime object and I need to retrieve the military time zone abbreviation (e.g. T for UTC-07:00, U for UTC-08:00, Z for UTC±00:00).

See http://en.wikipedia.org/wiki/List_of_military_time_zones

Here's how I'm currently doing it:

int offset = dt.getZone().toTimeZone().getRawOffset() / (60 * 60 * 1000);
String timeZoneCode = timeZoneCodeMap.get(offset);

where timeZoneCodeMap is a HashMap<Integer, String> that is initialized with entries like the following

timeZoneCodeMap.put(1, "A");
timeZoneCodeMap.put(2, "B");
timeZoneCodeMap.put(3, "C");
...
timeZoneCodeMap.put(-10, "W");
timeZoneCodeMap.put(-11, "X");
timeZoneCodeMap.put(-12, "Y");      
timeZoneCodeMap.put(0, "Z");

Does there exist a function or library (in Joda or otherwise) that already contains a mapping of time zones to military abbreviations?

Feel free to let me know if there is a better way to calculate the offset as well.

回答1:

This is such little code, that you might as well just do it yourself ...

static final String MAPPING = "YXWVUTSRQPONZABCDEFGHIKLM";
...
  String timeZoneCode = MAPPING.substring(offset + 12, offset + 13);