简体   繁体   中英

Java - how can I obtain a K-hour-shifted TimeZone?

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?

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...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM