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


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


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

用法:

public Year minus(TemporalAmount amountToSubtract)

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


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

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

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

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

示例1:

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

示例2:

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

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



相關用法


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