Saturday, October 11, 2025
HomeLanguagesJavaZoneOffset ofHours(int) method in Java with Examples

ZoneOffset ofHours(int) method in Java with Examples

The ofHours(int) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offset in hours passed as the parameter. This method takes the hours as parameter in the form of int and converts it into the ZoneOffset. The maximum supported range is from +18:00 to -18:00 inclusive.

Syntax:

public static ZoneOffset ofHours(int hours)

Parameters: This method accepts a parameter hours which is int to be converted into an ZoneOffset instance.

Return Value: This method returns a ZoneOffset instance parsed from the specified hours.

Exception: This method throws DateTimeException if the hours is invalid.

Below examples illustrate the ZoneOffset.ofHours() method:

Example 1:




// Java code to illustrate ofHours() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the hours
        int hours = 10;
  
        // ZoneOffset using ofHours() method
        ZoneOffset zoneOffset
            = ZoneOffset.ofHours(hours);
  
        System.out.println(zoneOffset);
    }
}


Output:

+10:00

Example 2: To demonstrate DateTimeException




// Java code to illustrate ofHours() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the invalid hours
        int hours = 20;
  
        try {
            // ZoneOffset using ofHours() method
            ZoneOffset zoneOffset
                = ZoneOffset.ofHours(hours);
        }
  
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output:

java.time.DateTimeException: Zone offset hours not in valid range: value 20 is not in the range -18 to 18

Reference: Oracle Doc

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6719 POSTS0 COMMENTS
Nicole Veronica
11882 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS