tags:

views:

65

answers:

2

I will be retrieving values from the range -12 to +12 & I need to convert it to a specific timezone format string.

e.g.

-3 becomes -03:00
0 becomes Z
4 becomes +04:00

Is there any readymade utility that I've overlooked that does the same thing in JDK6 ?

Thanks

A: 

Have a look at TimeZone

Convert your input like:

int offset = -3;
String cv = TimeZone.getTimeZone("GMT"+String.valueOf(offset)).getID();

...string cv will contain the value "GMT-03:00" which you can substring as required.

...as a specific example;

public String getTZfromInt(int offset) {
if (int == 0) return "Z";
if (offset < 0)  return TimeZone.getTimeZone("GMT"+String.valueOf(offset)).getID().substr(3);
else return TimeZone.getTimeZone("GMT+"+String.valueOf(offset)).getID().substr(3);
}
Steve De Caux
Don't forget to account for the `+` sign if offset is positive.
notnoop
Good point ! Edit accordingly
Steve De Caux
+1  A: 

There isn't anything built-in to the JDK that will give you exactly the format you've specified (without some manipulation). SimpleDateFormat("Z") is close but that gives you a timezone in RFC 822 format which is not exactly what you're asking for.

You might as well just keep things simple and do this:

public static String formatTimeZone(int offset) {
    if (offset > 12 || offset < -12) {
        throw new IllegalArgumentException("Invalid timezone offset " + offset);
    }
    if (offset >= 10) {
         return "+" + offset + ":00";
    } else if (offset > 0) {
         return "+0" + offset + ":00";
    } else if (offset == 0) {
         return "Z";
    } else if (offset > -10) {
         return "-0" + (-offset) + ":00";
    } else {
         return offset + ":00";
    }
}
Asaph
SimpleDateFormat("z") will treat timezone as General time zone according to javadoc. This will return zone name or GMT offset in format sign hours:minutes in two digits format.
Rastislav Komara
@Rastislav Komara: I suppose the OP could use `SimpleDateFormat("z")` and parse out the end piece. But offset zero is a special case for the OP too. So it still gets a little messy.
Asaph