开发者

Any utility in the JDK to format a timezone into a specific string

开发者 https://www.devze.com 2022-12-14 21:56 出处:网络
I will be retrieving values from the range -12 to开发者_JS百科 +12 & I need to convert it to a specific timezone format string.

I will be retrieving values from the range -12 to开发者_JS百科 +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 ?


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";
    }
}


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号