Java Time Zone code help in GMT

Can you help in understanding this code. Looks like it is getting timezone As an off-set from GMT in hours. But not sure...

what is the consideration for DST in the code ?

Please help.

// 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;
    }
Jon Skeet
people
quotationmark

Firstly, code like this is almost always a mistake. Java provides quite a lot of options when it comes to text formatting for date/time types... I'd recommend using java.time as far as possible.

However, in terms of how this code takes DST into account, this is the relevant line:

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

The creation of a Calendar is pointless - this would be simpler:

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

They both do the same thing: get the current offset from UTC. From 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.

That's only appropriate for the current time, of course - it might have been different a minute ago, and it may be different in a minute's time. If you've just formatted the current date/time, it's possible that between that formatting and this formatting, the time zone offset has changed. Yet another reason to avoid this code.

people

See more on this question at Stackoverflow