HomeLanguagesJavaYear from() Method in Java with Examples

Year from() Method in Java with Examples

from() method of the Year class used to get instance of Year from TemporalAccessor object passed as parameter. A TemporalAccessor represents an arbitrary set of date and time information and this method helps to get a year object based on the specified TemporalAccessor object.

Syntax:

public static Year from(TemporalAccessor temporal)

Parameters: This method accepts temporal as parameter which is the temporal object. It should not be null.

Return value: This method returns the year object.

Exception: This method throws following Exceptions:

  • DateTimeException – if unable to convert to a Year.

Below programs illustrate the from() method:
Program 1:




// Java program to demonstrate
// Year.from() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a temporal object
        LocalDate date = LocalDate.parse("2007-12-03");
  
        // print instance
        System.out.println("LocalDate :"
                           + date);
  
        // apply from method of Year class
        Year year = Year.from(date);
  
        // print instance
        System.out.println("Year get from"
                           + " method: "
                           + year);
    }
}


Output:

LocalDate :2007-12-03
Year get from method: 2007

Program 2:




// Java program to demonstrate
// Year.from() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // create a temporal object
        LocalDate ins = LocalDate.parse("2018-11-27");
  
        // print instance
        System.out.println("LocalDate :"
                           + ins);
  
        // apply from method of Year class
        Year year = Year.from(ins);
  
        // print instance
        System.out.println("Year get from"
                           + " method: "
                           + year);
    }
}


Output:

LocalDate :2018-11-27
Year get from method: 2018

References: https://docs.oracle.com/javase/10/docs/api/java/time/Year.html#from(java.time.temporal.Temporal)

RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32561 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6937 POSTS0 COMMENTS
Nicole Veronica
12057 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12176 POSTS0 COMMENTS
Shaida Kate Naidoo
7075 POSTS0 COMMENTS
Ted Musemwa
7319 POSTS0 COMMENTS
Thapelo Manthata
7028 POSTS0 COMMENTS
Umr Jansen
7022 POSTS0 COMMENTS