OffsetDateTime getOffset() method in Java with examples

The zone offset, such as "+05:00," is obtained via the Java OffsetDateTime class's getOffset() function.

Syntax:

public ZoneOffset getOffset()

Parameter: There are no parameters that are accepted by this method.

Return Value: Instead of null, it returns the zone offset.

Example 1:

An OffsetDateTime object is parsed and its time zone offset is retrieved in the main method of the class getOffsetExample1, which is defined in the Java code. Once the given string has been parsed, an OffsetDateTime object is created. Next, the parsed date-time and its offset are sent to the console. The offset from the parsed date-time is retrieved using the getOffset() method. Illustrations of how to handle and display date-time data with a defined time zone offset are shown here using OffsetDateTime and ZoneOffset.

Implementation:

FileName: getOffsetExample1.java

Output:

 
The Parsed Date-Time is given by: 2024-06-27T13:30:30+05:00
The Offset is given by: +05:00   

Example 2:

With the given date and time (June 27, 2024, at 13:30:30) and a custom time zone offset of +5 hours using the ZoneOffset.ofHours(5) method, the Java code creates an OffsetDateTime object. Next, it uses the getOffset() function to retrieve this offset, and it releases the offset value as well as the OffsetDateTime instance to the console. This illustrates how to handle several time zones with ease by showing how to construct and modify date-time objects in Java with specified offsets.

Implementation:

FileName: getOffsetExample2.java

Output:

 
The Custom Offset Date-Time is given by: 2024-06-27T13:30:30+05:00
The Offset is given by: +05:00