當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Period withMonths()用法及代碼示例


期間類的withMonths()方法用於獲取指定月數的期間。這個月數作為參數傳遞為整數值。

用法:

public Period withMonths(int numberOfMonths)

參數:此方法接受參數numberOfMonths,該參數是此期間要更改的月數。


返回值:此函數返回以傳遞的月數為參數的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-



相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 Period withMonths() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。