ZoneOffset from(TemporalAccessor) method in Java with Examples

The from(TemporalAccessor) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offset in temporalAccessor passed as the parameter. This method takes the temporalAccessor as parameter in the form of TemporalAccessor and converts it into the ZoneOffset.

Syntax:

public static ZoneOffset
  from(TemporalAccessor temporalAccessor)

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

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

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

Below examples illustrate the ZoneOffset.from() method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate from() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the temporalAccessor
        TemporalAccessor temporalAccessor
            = ZonedDateTime.now();
  
        // ZoneOffset using from() method
        ZoneOffset zoneOffset
            = ZoneOffset.from(temporalAccessor);
  
        System.out.println(zoneOffset);
    }
}

chevron_right


Output:

Z

Example 2: To demonstrate DateTimeException

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate from() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        try {
            // ZoneOffset using from() method
            ZoneOffset zoneOffset
                = ZoneOffset.from(LocalDate.now());
        }
  
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

chevron_right


Output:

java.time.DateTimeException:
 Unable to obtain ZoneOffset from TemporalAccessor:
 2018-12-11 of type java.time.LocalDate

Reference: Oracle Doc



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.