Java Period toTotalMonths()方法及示例

Java Period toTotalMonths()方法及示例

Period类toTotalMonths() 方法用于获取给定周期内的总月数。它返回一个描述相同内容的长值。

语法

public long toTotalMonths()

参数: 该方法不接受任何参数。

返回: 该函数返回长值,即该周期内的总月数。

下面是Period.toTotalMonths()方法的实现。

例子 1:

// Java code to demonstrate toTotalMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be toTotalMonthsd
        String period = "P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the total number of months
        // using toTotalMonths() method
        System.out.println("Total number of Months"
                           + " in this Period: "
                           + p.toTotalMonths());
    }
}

输出:

Period: P1Y2M21D
Total number of Months in this Period: 14

例2:

// Java code to demonstrate toTotalMonths() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be toTotalMonthsd
        String period = "-P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the total number of months
        // using toTotalMonths() method
        System.out.println("Total number of Months"
                           + " in this Period: "
                           + p.toTotalMonths());
    }
}

输出:

Period: P-1Y-2M-21D
Total number of Months in this Period: -14

参考资料: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#toTotalMonths-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程