0

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

Łukasz
  • 1,980
  • 6
  • 32
  • 52
  • check here http://stackoverflow.com/questions/10545960/how-to-tackle-daylight-savings-using-timezone-in-java – Karthik Sep 29 '16 at 07:24

2 Answers2

2

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
Jens
  • 67,715
  • 15
  • 98
  • 113
1

Check whether DST is active in java .

TimeZone tz = TimeZone.getTimeZone("America/New_York");
boolean inDs = tz.inDaylightTime(new Date());

Below code give you with DST time

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));
Karthik
  • 545
  • 6
  • 23