I suggest you use ZoneId#getRules
to get the ZoneOffset
, from which you can get the hours and minutes if required.
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
// Test
ZoneOffset offset = convertToZoneOffset(ZoneId.of("Asia/Kolkata"));
System.out.println(offset);
long seconds = offset.getTotalSeconds();
long hours = TimeUnit.HOURS.convert(seconds, TimeUnit.SECONDS);
long minutes = TimeUnit.MINUTES.convert(seconds, TimeUnit.SECONDS) % 60;
System.out.println(hours);
System.out.println(minutes);
}
private static ZoneOffset convertToZoneOffset(final ZoneId zoneId) {
return zoneId.getRules().getOffset(Instant.now());
}
}
Output:
+05:30
5
30
ONLINE DEMO
The variant using a specific Unix epoch:
private static ZoneOffset convertToZoneOffset(final ZoneId zoneId, long epochSecond) {
return zoneId.getRules().getOffset(Instant.ofEpochSecond(epochSecond));
}
Also, if you need the hours to be rounded off, you can use the following statement in the code:
long hours = Math.round(seconds / 3600.0);
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.