Java中的Period getYears()方法

可以使用getYears()Java中Period类中的方法来获取特定Period的年数。此方法不需要任何参数,它返回期间中的年数。

演示此的程序如下

示例

import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      String period = "P5Y7M15D";
      Period p = Period.parse(period);
      System.out.println("The Period is: " + p);
      System.out.println("The number of years are: " + p.getYears());
   }
}

输出结果

The Period is: P5Y7M15D
The number of years are: 5

现在让我们了解上面的程序。

首先显示期间。然后使用该getYears()方法获得期间的年数并显示。演示此代码段如下所示:

String period = "P5Y7M15D";
Period p = Period.parse(period);
System.out.println("The Period is: " + p);
System.out.println("The number of years are: " + p.getYears());