📌  相关文章
📜  Java中的 YearMonth plus(long,unit) 方法及示例

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

Java中的 YearMonth plus(long,unit) 方法及示例

YearMonth类的plus(long, unit)方法用于在将指定数量的 TemporalUnit 添加到此 Year-month 对象后返回此 Year-month 的副本。如果指定的单位不能添加到年月,则抛出异常。此实例是不可变的,不受此方法调用的影响。

句法:

public YearMonth plus(long amountToadd, TemporalUnit unit)

参数:此方法接受两个参数:

  • amountToadd :此参数表示要添加到结果中的单位数量。
  • unit该参数表示添加量的单位。

返回值:此方法基于此年月返回一个年月,并添加指定的金额。

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

  • DateTimeException –如果无法添加,则会引发此异常。
  • UnsupportedTemporalTypeException –如果不支持该单元,则会引发此异常。
  • ArithmeticException –如果发生数字溢出,则会引发此异常。

下面的程序说明了 plus(long, unit) 方法:

方案一:

Java
// Java program to demonstrate
// YearMonth.plus(long, unit) 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(2017, 8);
 
        // print instance
        System.out.println("YearMonth :"
                           + thisYearMonth);
 
        // apply plus(long, unit) method
        // adding 15 Years
        YearMonth value
            = thisYearMonth.plus(15, ChronoUnit.YEARS);
 
        // print result
        System.out.println("After addition YearMonth: "
                           + value);
    }
}


Java
// Java program to demonstrate
// YearMonth.plus(long, unit) 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, 12);
 
        // print instance
        System.out.println("YearMonth :"
                           + thisYearMonth);
 
        // apply plus(long, unit) method
        // adding 30 Months
        YearMonth value
            = thisYearMonth.plus(30, ChronoUnit.MONTHS);
 
        // print result
        System.out.println("After addition YearMonth: "
                           + value);
    }
}


输出:
YearMonth :2017-08
After addition YearMonth: 2032-08

方案二:

Java

// Java program to demonstrate
// YearMonth.plus(long, unit) 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, 12);
 
        // print instance
        System.out.println("YearMonth :"
                           + thisYearMonth);
 
        // apply plus(long, unit) method
        // adding 30 Months
        YearMonth value
            = thisYearMonth.plus(30, ChronoUnit.MONTHS);
 
        // print result
        System.out.println("After addition YearMonth: "
                           + value);
    }
}
输出:
YearMonth :2019-12
After addition YearMonth: 2022-06

参考:
https://docs.oracle.com/javase/10/docs/api/java /time/Year.html#plus(long, Java Java)