0

I have a TimeZone variable (DEFAULT_TIME_ZONE) obtained by following code

TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone("GMT");

And now I want to get another TimeZone that is shifted K hours from DEFAULT_TIME_ZONE.

How can I do that?

Season
  • 1,178
  • 2
  • 22
  • 42

1 Answers1

1

If you actually mean "a time zone which has a permanent constant offset from UTC", that's easy:

int offsetMillis = (int) TimeUnit.HOURS.toMillis(offsetHours);
TimeZone zone = new SimpleTimeZone(offsetMillis, "some id");

If you mean a time zone which obeys the same daylight saving rules as another time zone, but is shifted by a fixed offset, that would be a bit harder - but also less useful, I'd argue.

Note that if you use Joda Time, you can achieve the former with:

DateTimeZone zone = DateTimeZone.forOffsetHours(offsetHours);

(And you'll have a far nicer API to work with, too...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for quick reply. I have another question, how can I get the hour difference between 2 TimeZones? – Season Feb 23 '15 at 08:28
  • @Season: I suggest you ask a new question for that, with a lot more detail - it really depends on what you're trying to achieve. – Jon Skeet Feb 23 '15 at 08:29
  • 1
    @Season - keep in mind that without a specific date and time, you *can't* always get the difference between two time zones. – Matt Johnson-Pint Feb 23 '15 at 20:25