📜  Java中的 YearMonth plusYears() 方法及示例

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

Java中的 YearMonth plusYears() 方法及示例

Java中YearMonth 类plusYears()方法用于返回此 YearMonth 的副本,其中添加了指定的年数。

句法:

public YearMonth plusYears(long yearsToAdd)

参数:此方法接受yearsToAdd作为参数,表示要添加到当前 YearMonth 对象的年份。它可能是负面的。

返回值:它根据添加的年份返回基于此年月的YearMonth

异常:如果结果超出支持的范围,此方法将引发DateTimeException

下面的程序说明了Java中 YearMonth 的 plusYears() 方法:

方案一:

// Java program to demonstrate
// YearMonth.plusYears() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // Create YearMonth object
        YearMonth yearmonth
            = YearMonth.parse("2020-05");
  
        // Apply plusYears() method
        // of YearMonth class
        YearMonth result
            = yearmonth.plusYears(5);
        // It will add 5 years into May 2020
        // So it will be May 2025
  
        // print results
        System.out.println(
            "Modified YearMonth: "
            + result);
    }
}
输出:
Modified YearMonth: 2025-05

方案二:

// Java program to demonstrate
// YearMonth.plusYears() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // Create YearMonth object
        YearMonth yearmonth
            = YearMonth.of(2019, 10);
        // It is October 2019
  
        // apply plusYears() method
        // of YearMonth class
        YearMonth result
            = yearmonth.plusYears(10);
        // YearMonth will become October 2029
  
        // print only modified year
        System.out.println(
            "Modified Year: "
            + result.get(ChronoField.YEAR));
    }
}
输出:
Modified Year: 2029

参考资料: https: Java/time/YearMonth.html#plusYears(long)