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


Java YearMonth minusMonths()用法及代碼示例

Java中YearMonth類的minusMonths()方法用於返回該YearMonth的副本,其中減去指定的月數。

用法:

public YearMonth minusMonths(
        long monthsToSubtract)

參數:此方法接受monthsToSubtract作為參數,代表要減去的月份。可能是負麵的。



返回值:它基於此year-month減去後的月份返回YearMonth。

異常:如果結果超出支持的範圍,則此方法將引發DateTimeException。

以下示例程序旨在說明Java中YearMonth的minusMonths()方法:

程序1:

// Java program to demonstrate 
// YearMonth.minusMonths() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create YearMonth object 
        YearMonth yearmonth 
            = YearMonth.parse("2020-05"); 
        // It is May 2020 
  
        // apply minusMonths() method 
        // of YearMonth class 
        YearMonth result 
            = yearmonth.minusMonths(2); 
        // It subtracts 2 months from May 2020 
        // So it will be March 2020 
  
        // print year and month both 
        System.out.println("Modified YearMonth:"
                           + result); 
    } 
}
輸出:
Modified YearMonth:2020-03

程序2:

// Java program to demonstrate 
// YearMonth.minusMonths() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create YearMonth object 
        YearMonth yearmonth 
            = YearMonth.parse("2019-10"); 
  
        // apply minusMonths() method 
        // of YearMonth class 
        YearMonth result 
            = yearmonth.minusMonths(10); 
        // Subtrating 10 months will turn it into 
        // December of 2018 (previous year) 
  
        // print year and month both 
        System.out.println( 
            "Modified YearMonth:"
            + result); 
    } 
}
輸出:
Modified YearMonth:2018-12

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#minusMonths(long)




相關用法


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