Java GMT 时区代码帮助

Java Time Zone code help in GMT

你能帮助理解这段代码吗?看起来它正在将时区作为 GMT 的偏移量以小时为单位。但不确定...

代码中夏令时的注意事项是什么?

请帮忙。

// Time zone offset in hours from GMT
    TimeZone timezone = TimeZone.getDefault();
    String result  = CCUtil.getTimeZoneOffSet(timezone);


CCUtil.java         
public static String getTimeZoneOffSet(TimeZone tz) {
        String result = "";
        int offSet = tz.getOffset(Calendar.getInstance().getTimeInMillis());
        String sign = "-";
        if (offSet >= 0)
            sign = "+";
        else
            offSet = Integer.parseInt(Integer.toString(offSet).substring(1));

        int minutes = offSet / (1000 * 60);
        int hours = minutes / 60;
        minutes = minutes % 60;
        result = sign + lpad(Integer.toString(hours), "00") + ":"
                + lpad(Integer.toString(minutes), "00");

        return result;
    }

    private static String lpad(String str, String pad) {
        int strLen = str.length();
        int padLen = pad.length();
        String result = str;
        if (strLen < padLen) {
            result = pad.substring(0, padLen - strLen) + result;
        }
        return result;
    }

首先,像这样的代码几乎总是一个错误。 Java 为 date/time 类型的文本格式提供了很多选项...我建议尽可能使用 java.time

但是,就此代码如何考虑 DST 而言,这是相关行:

int offSet = tz.getOffset(Calendar.getInstance().getTimeInMillis());

创建 Calendar 毫无意义 - 这会更简单:

int offSet = tz.getOffset(System.currentTimeMillis());

它们都做同样的事情:获取与 UTC 的 current 偏移量。来自 TimeZone.getOffset:

Returns the offset of this time zone from UTC at the specified date. If Daylight Saving Time is in effect at the specified date, the offset value is adjusted with the amount of daylight saving.

那是适合当前时间,当然——一分钟前可能不一样,一分钟后可能不一样。如果您刚刚格式化了当前的 date/time,可能在该格式和 this 格式之间,时区偏移发生了变化。避免此代码的另一个原因。