19

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.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
jewbix.cube
  • 485
  • 6
  • 19
  • 2
    http://sourceforge.net/p/joda-time/discussion/337835/thread/51d091f2/ – assylias Nov 13 '13 at 22:30
  • I've not tried this with JODA but I know that to get this to work with java.util.Date (which sucks, I know) I had to do a bit of manual finagling. – Taylor Nov 13 '13 at 22:40
  • 5
    As assylias points out, no such support in [Joda-Time](http://www.joda.org/joda-time/). [JSR 310: Date and Time API](http://jcp.org/en/jsr/detail?id=310) is the successor to Joda-Time, and is integrated with the upcoming Java 8. If you care about this feature, you might check with the JSR team to see about adding support. It may be only a matter of adding a formatter implementation (I don't know, I haven't thought it through). The team has been open to contributors in the past, and may still accept your input or code donation. – Basil Bourque Nov 14 '13 at 01:42
  • 2
    What's so bad about writing your own method? – Anubian Noob Nov 14 '13 at 16:23
  • 7
    Because a better one might already exist. – jewbix.cube Nov 14 '13 at 19:35
  • 3
    Be aware that not all time zones use a whole number of hours. Quite a few time zones use half and quarter hours, and until 1955 Bombay time was UTC+4:51. – Ben Nov 18 '13 at 14:59
  • 1
    Today I was instructed to just use Zulu time, so I no longer need this code. If someone still cares enough to try to get a solution into JSR 310, I'm sure someone out there would appreciate it someday. – jewbix.cube Nov 19 '13 at 02:04

1 Answers1

2

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);
Eamonn O'Brien-Strain
  • 3,352
  • 1
  • 23
  • 33
  • Accepting this as more clever alternative to using a HashMap, assuming that the offset has already been normalized to account for half and quarter hours as @Ben mentioned in his comment on my question. – jewbix.cube Nov 25 '13 at 20:33