📜  Java中 of() 方法及示例

📅  最后修改于: 2022-05-13 01:55:48.411000             🧑  作者: Mango

Java中 of() 方法及示例

Period 类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-