Java Period withMonths()方法及示例

Java Period withMonths()方法及示例

Period类withMonths() 方法是用来获得一个具有指定月数的周期。该月数作为参数以整数形式传递。

语法

public Period withMonths(int numberOfMonths)

参数: 该方法接受一个参数numberOfMonths,它是这个Period中要改变的月数。

返回: 该函数返回一个带有作为参数的月数的Period。

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

例子 1:

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

输出:

Period: P1Y2M21D
New Period: P1Y5M21D

例2:

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

输出:

Period: P-1Y-2M-21D
New Period: P-1Y-5M-21D

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程