Java中的Period getMonths()方法
可以使用getMonths()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 months are: " + p.getMonths());
}
}输出结果
The Period is: P5Y7M15D The number of months are: 7
现在让我们了解上面的程序。
首先显示期间。然后,使用该getMonths()方法获得期间的月数并显示出来。演示此代码段如下所示:
String period = "P5Y7M15D";
Period p = Period.parse(period);
System.out.println("The Period is: " + p);
System.out.println("The number of months are: " + p.getMonths());