当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java YearMonth plus(TemporalAmount)用法及代码示例


在将指定数量的TemporalAmount添加到Year Yearth对象之后,使用YearMonth类的plus(TemporalAmount)方法返回Year Yearth的副本。如果无法将指定的单位添加到YearMonth,则会引发异常。传递的TemporalAmount是根据Period对象创建的。此实例是不可变的,不受此方法调用的影响。

用法:

public YearMonth plus(TemporalAmount amountToadd)

参数:此方法仅接受一个参数TemporalAmount,该参数表示要添加到YearMonth对象的数量。


返回值:此方法基于此YearMonth返回YearMonth,并添加指定的数量。

异常:此方法引发以下异常:

  • DateTimeException-如果无法进行加法运算,则抛出此异常。
  • ArithmeticException-如果发生数字溢出,则抛出此异常。

以下示例程序旨在说明plus(TemporalAmount amountToadd)方法:

示例1:

// Java program to demonstrate 
// YearMonth.plus(TemporalAmount amountToadd) 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 
        // plus() method 
        YearMonth value 
            = thisYearMonth.plus( 
                Period.ofYears(120)); 
  
        // print result 
        System.out.println("Value after addition: "
                           + value); 
    } 
}
输出:
YearMonth :2019-11
Value after addition: 2139-11

示例2:

// Java program to demonstrate 
// YearMonth.plus(TemporalAmount amountToadd) 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 
        // plus() method 
        YearMonth value 
            = thisYearMonth.plus( 
                Period.ofMonths(200)); 
  
        // print result 
        System.out.println("Value after addition: "
                           + value); 
    } 
}
输出:
YearMonth :2022-11
Value after addition: 2039-07

参考文献:
https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#plus(java.time.temporal.TemporalAmount)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 YearMonth plus(TemporalAmount) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。