In my Android app, I use the calendar in various time zones. This way I can adjust the app operation to local conditions.
runDate = Calendar.getInstance(); // will display tides for this date/time
useThisTZ = TimeZone.getTimeZone("US/Pacific");
runDate.setTimeZone(useThisTZ);
I need to adapt to nautical or military time zones. These are geographic rather than civil. I need to determine what identifiers I can pass into the getTimeZone function to do this. I have tried the time zone code "A" which identified the Alpha time zone (UTC + 1). However this placed the calendar into the GMT zone which would normally be called Zulu.
Does anybody know if these identifiers are available and what they might be.
ZoneOffset and OffsetDateTime from java.time
Consider using java.time, the modern Java date and time API, for your date and time work. Nautical (or military) time zones are mere offsets in whole hours from UTC, so we don’t need any fancy time zone rules taking summer time (DST) and other anomalies into account, for there aren’t any. A plain
ZoneOffset
will do.The time zone names are not built in. We need to code the conversion ourselves. One way to do it is through an array in which we can look up a time zone name and get the offset out:
Example use:
When I ran this snippet just now, the output was:
You notice that the offset is +01:00 corresponding to nautical time zone A. Please try the other time zones too.
As the code stands it will throw an
ArrayIndexOutOfBounsException
if the char is beyond upper caseZ
. I leave it to you to build in the necessary check.Edit:
If that were me, I would take the opportunity to switch over from the outdated
Calendar
class to java.time. Also because, as I tried to indicate, when you use the old-fashionedTimeZone
class, you are carrying with you everything that is needed for general time zones when all you need is an offset. If you insist on usingCalendar
and feeding it aTimeZone
, the conversion is easy enough. Assuming your are using ThreeTenABP (see below):This is the time zone ID you were asking for. The others are similar, you can construct them yourself. If in doubt, run my code at get them from there. For feeding into a
Calendar
you don’t need the ID, of course, you have already got theTimeZone
object.Still a bit better (or not quite so bad), even if you need an old-fashioned
Calendar
for your legacy code, you don’t need to deal with the confusing and poorly designedTimeZone
class. You may get yourCalendar
from this code:If using Java 8 (also if using Java 8 through desugaring, I suppose), the conversions are a bit shorter still,
TimeZone.getTimeZone(offset)
andGregorianCalendar.from(runDateTime.atZoneSameInstant(offset))
, respectively.Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.Links
java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).