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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。