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


Java YearMonth minus(TemporalAmount)用法及代碼示例


從Yearyearth對象減去指定的TemporalAmount數量後,使用YearMonth類的minus(TemporalAmount)方法返回Yearyear的副本。如果無法從YearMonth中減去指定的單位,則會引發異常。傳遞的TemporalAmount是根據Period對象創建的。此實例是不可變的,不受此方法調用的影響。

用法:

public YearMonth minus(TemporalAmount amountToSubtract)

參數:此方法僅接受一個參數TemporalAmount,該參數表示從YearMonth對象減去的數量。


返回值:此方法基於此YearMonth返回YearMonth,減去指定的數量。

異常:此方法引發以下異常:

  • DateTimeException-如果無法進行減法,則拋出此異常。
  • ArithmeticException-如果發生數字溢出,則拋出此異常。

以下示例程序旨在說明減號(TemporalAmount amountToSubtract)方法:

示例1:

// Java program to demonstrate 
// YearMonth.minus(TemporalAmount amountToSubtract) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a YearMonth object 
        YearMonth thisYearMonth = YearMonth.of(2019, 11); 
  
        // print instance 
        System.out.println("YearMonth :"
                           + thisYearMonth); 
  
        // create temporalAmount object from period class 
        // passing temporalAmount to 
        // minus() method 
        YearMonth value 
            = thisYearMonth.minus( 
                Period.ofYears(22)); 
  
        // print result 
        System.out.println("Value after Subtraction: "
                           + value); 
    } 
}
輸出:
YearMonth :2019-11
Value after Subtraction: 1997-11

示例2:

// Java program to demonstrate 
// YearMonth.minus(TemporalAmount amountToSubtract) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a YearMonth object 
        YearMonth thisYearMonth = YearMonth.of(2022, 11); 
  
        // print instance 
        System.out.println("YearMonth :"
                           + thisYearMonth); 
  
        // create temporalAmount object from period class 
        // passing temporalAmount to 
        // minus() method 
        YearMonth value 
            = thisYearMonth.minus( 
                Period.ofMonths(20)); 
  
        // print result 
        System.out.println("Value after Subtraction: "
                           + value); 
    } 
}
輸出:
YearMonth :2022-11
Value after Subtraction: 2021-03

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



相關用法


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