当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Year from()用法及代码示例


Year类的from()方法用于从作为参数传递的TemporalAccessor对象中获取Year的实例。 TemporalAccessor表示日期和时间信息的任意集合,此方法有助于根据指定的TemporalAccessor对象获取年份对象。

用法:

public static Year from(TemporalAccessor temporal)

参数:该方法接受作为时间对象的时间作为参数。它不能为空。


返回值:此方法返回年份对象。

异常:此方法引发以下异常:

  • DateTimeException-如果无法转换为年份。

以下示例程序旨在说明from()方法:
示例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); 
    } 
}
输出:
LocalDate :2007-12-03
Year get from method: 2007

示例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); 
    } 
}
输出:
LocalDate :2018-11-27
Year get from method: 2018

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



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Year from() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。