Łukasz Łukasz - 2 months ago 8
Java Question

TimeZone offset shows invalid value

Unless I do something wrong...

I live in Poland (GMT+2). By the time I write this we are in daylight saving time. The following code, however, says that the GMT time offset is only 1 hour instead of 2.

Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
System.out.println(mTimeZone);
int mGMTOffset = mTimeZone.getRawOffset();
System.out.printf("GMT offset is %s hours", TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));


prints GMT offset is 1 hours

Same happens for other timezones, for example New York, which is GMT-4:

Calendar mCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));


prints GMT offset is -5 hours

Answer

There are two methods the TimeZone you have to use:

you can check if the a date is in DaylightSaveTime with:

mTimeZone.inDaylightTime(date)

And if this is True you have to add the value of

mTimeZone.getDSTSavings()

to the Offset:

Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
System.out.println("TimeZone: "+mTimeZone);
int mGMTOffset = mTimeZone.getRawOffset();
if (mTimeZone.inDaylightTime(mCalendar.getTime())){
    mGMTOffset += mTimeZone.getDSTSavings();
}
System.out.printf("GMT offset is %s hours", 
TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));

output:

GMT offset is 2 hours