📌  相关文章
📜  Java中的 YearMonth minus(TemporalAmount) 方法及示例

📅  最后修改于: 2022-05-13 01:55:50.657000             🧑  作者: Mango

Java中的 YearMonth minus(TemporalAmount) 方法及示例

YearMonth类的minus(TemporalAmount)方法用于在从该 YearMonth 对象中减去指定数量的 TemporalAmount 后返回该 YearMonth 的副本。如果不能从 YearMonth 中减去指定的单位,则会引发异常。传递的 TemporalAmount 是从 Period 对象创建的。此实例是不可变的,不受此方法调用的影响。

句法:

public YearMonth minus(TemporalAmount amountToSubtract)

参数:此方法仅接受一个参数TemporalAmount ,该参数表示要从 YearMonth 对象中减去的金额。

返回值:此方法基于此 YearMonth 返回一个 YearMonth,并减去指定的金额。

异常:此方法抛出以下异常:

  • DateTimeException –如果无法进行减法,则会引发此异常。
  • ArithmeticException –如果发生数字溢出,则会引发此异常。

下面的程序说明了减法(TemporalAmount amountToSubtract)方法:

方案一:

// 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

方案二:

// 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 Java Java)