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


Java Period of()用法及代碼示例


周期類的of()方法用於從給定的年,月和天數中獲取一個周期作為參數。這些參數以整數形式接受。此方法返回具有給定年數,月數和天數的Period。

用法:

public static Period of(
        int numberOfYears, 
        int numberOfMonths,
        int numberOfDays)

參數:此方法接受以下參數:


  • numberOfYears:用於表示可能為負的年份。
  • numberOfMonths:用於表示可能為負的月數。
  • numberOfDays:用於表示可能為負的天數。

返回值:此函數返回期間,該期間是使用給定的年,月和天數解析的Period對象。

下麵是Period.of()方法的實現:

示例1:

// Java code to demonstrate of() method 
  
import java.time.Period; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the number of Years 
        int numberOfYears = 1; 
  
        // Get the number of Months 
        int numberOfMonths = 5; 
  
        // Get the number of Days 
        int numberOfDays = 21; 
  
        // Parse the given amounts into Period 
        // using of() method 
        Period p 
            = Period.of(numberOfYears, 
                        numberOfMonths, 
                        numberOfDays); 
  
        System.out.println(p.getYears() + " Years\n"
                           + p.getMonths() + " Months\n"
                           + p.getDays() + " Days"); 
    } 
}
輸出:
1 Years
5 Months
21 Days

示例2:

// Java code to demonstrate of() method 
  
import java.time.Period; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the number of Years 
        int numberOfYears = -2; 
  
        // Get the number of Months 
        int numberOfMonths = 10; 
  
        // Get the number of Days 
        int numberOfDays = -11; 
  
        // Parse the given amounts into Period 
        // using of() method 
        Period p 
            = Period.of(numberOfYears, 
                        numberOfMonths, 
                        numberOfDays); 
  
        System.out.println(p.getYears() + " Years\n"
                           + p.getMonths() + " Months\n"
                           + p.getDays() + " Days"); 
    } 
}
輸出:
-2 Years
10 Months
-11 Days

參考: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#of-int-int-int-



相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 Period of() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。