📜  Java中的 Period withYears() 方法和示例

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

Java中的 Period withYears() 方法和示例

Period 类withYears()方法用于获取具有指定年数的期间。这个年数作为整数值作为参数传递。

句法:

public Period withYears(int numberOfYears)

参数:此方法接受参数numberOfYears ,这是此期间要更改的年数。

返回:此函数返回一个以年数作为参数传递的Period

下面是 Period.withYears() 方法的实现:

示例 1:

// Java code to demonstrate withYears() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be withYearsd
        String period = "P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the number of years
        int numberOfYears = 5;
  
        // Change the numberOfYears of this Period
        // using withYears() method
        System.out.println("New Period: "
                           + p.withYears(numberOfYears));
    }
}
输出:
Period: P1Y2M21D
New Period: P5Y2M21D

示例 2:

// Java code to demonstrate withYears() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be withYearsd
        String period = "-P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the number of years
        int numberOfYears = -5;
  
        // Change the numberOfYears of this Period
        // using withYears() method
        System.out.println("New Period: "
                           + p.withYears(numberOfYears));
    }
}
输出:
Period: P-1Y-2M-21D
New Period: P-5Y-2M-21D

参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/Period.html#withYears-int-