Duration
is the wrong class. There is zero duration between "now" in one time zone and "now" in another. For a fun but memorable way to think about this, see here.
You appear to be seeking to know the current offset from UTC for a given time zone. You can use the ZonedDateTime
class for that:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
ZoneOffset offset = zdt.getOffset();
int offsetMinutes = offset.getTotalSeconds() / 60;
double offsetHours = ((double) offsetMinutes) / 60;
System.out.println(offsetHours); // 5.5
You could also just use ZonedDateTime.now()
on the first line, if you want to use the computer's current time zone.
With regard to LocalTime
- that is just the time portion (hours, minutes, seconds, and smaller). Since there is no date associated, you can't necessarily determine which time zone offset it belongs to. There is more than one date that "today" going on at any given moment. Time zone offsets range from UTC-12 to UTC+14, so there are indeed values where the same time of day is happening on two different dates somewhere on the planet.
As an example, 08:00:00
in Hawaii (Pacific/Honolulu
) on 2019-01-01 is also 08:00:00
in Kiribati (Pacific/Kiritimati
), but on 2019-01-02 - the following date! (Reference here.) Thus, if you had a LocalTime
object with 08:00:00
and it was 08:00:00
in one of those two zones, you'd not be able to tell which one it was, or what the corresponding UTC offset should be.
Also, keep in mind that time zone offsets are not limited to whole hours. There are present-day time zones with half-hour and 45-minute offset. Historically, there have been others.
Lastly, keep in mind that an offset is not necessarily enough to identify a time zone. Many time zones share offsets at some points in time, but differ in others. See "Time Zone != Offset" in the timezone tag wiki.
Oh, and about your results getting 2
in one direction and -3
in the other - this is a rounding error due to your integer division. If you print out the seconds value, you'll notice they are one second apart (10799
, vs -10800
). Dig closer and you'll find that "now" included fractional seconds that were truncated with the getSeconds
call. (You called .now()
twice, so they were at slightly different times.)