Java ZoneOffset class allows us to manage time-zones effectively. Each country follows a certain timezone on top of that there is a day-light saving concept that comes into picture. To manage time-zones effectively and correctly, ZoneOffset provides multiple useful methods. ZoneOffset represents the amount of time that a timezone differs from Greenwich/UTC, this is usually represented by hours and minutes such as a – or +01:00.
Java ZoneOffset class:
public final class ZoneOffset extends ZoneId implements TemporalAccessor, TemporalAdjuster, Comparable<ZoneOffset>, Serializable
Java ZoneOffset – Method Summary
Method | Description |
---|---|
int get(TemporalField field) | This method returns the value of the specified field from this offset as an integer. |
Temporal adjustInto(Temporal temporal) | It adjusts the specified temporal object to have the same offset as this object. |
static ZoneOffset of(String offsetId) | It returns the instance of ZoneOffset using the specified offset Id. |
static ZoneOffset ofHoursMinutes(int hours, int minutes) | It returns an instance of ZoneOffset using the specified hours and minutes as an offset |
static ZoneOffset ofHours(int hours) | It returns an instance of ZoneOffset using the specified hours as offset. |
boolean isSupported(TemporalField field) | Checks if the specified temporal field is supported by this offset. |
ValueRange range(TemporalField field) | It returns the range of the valid values for the specified field. |
int hashCode() | Returns hash code of this offset. |
String toString() | Returns the offset as a String value. |
int getTotalSeconds() | Returns the time zone offset in seconds. |
ZoneRules getRules() | Returns the rules associated with the time-zone |
Java ZoneOffset – ofHours() & ofHoursMinutes() methods example
These methods are used to specify an offset in hours & minutes. The method ofHours()
is used to specify the offset in hours and to specify it in hour & minutes both use ofHoursMinutes()
method.
import java.time.ZoneOffset; public class JavaExample { public static void main(String[] args) { ZoneOffset zOffset = ZoneOffset.ofHours(2); System.out.println(zOffset); ZoneOffset zOffset2 = ZoneOffset.ofHoursMinutes(1,30); System.out.println(zOffset2); } }
Output:
+02:00 +01:30
Java ZoneOffset example – Finding the zone offset of a Zone Id
In this example we are finding the zone offset of Indian Time (Zone id: Asia/Kolkata
). This offset represents the time difference between the current time-zone (Indian Time) and UTC
time zone.
import java.time.*; public class JavaExample { public static void main(String[] args) { LocalDateTime datetime = LocalDateTime.now(); ZoneId zone = ZoneId.of("Asia/Kolkata"); ZoneOffset zoneoffset = zone.getRules().getOffset(datetime); System.out.println(zoneoffset); } }
Output:
+05:30
Reference
Leave a Reply