當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。