Java中的 YearMonth plusMonths() 方法及示例
Java中YearMonth类的plusMonths()方法用于获取此 YearMonth 的副本,其中添加了指定的月数。
句法:
public YearMonth plusMonths(long monthsToAdd)
参数:此方法接受monthToAdd作为参数,表示要添加到当前YearMonth 对象的月份。它可能是负面的。
返回值:它根据添加的月份返回基于此年月的YearMonth 。
异常:如果结果超出支持的范围,此方法将引发DateTimeException 。
下面的程序说明了Java中 YearMonth 的 plusMonths() 方法:
方案一:
// Java program to demonstrate
// YearMonth.plusMonths() 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 plusMonths() method
// of YearMonth class
// Adding 5 months into May 2020
// will turn it into October 2020
YearMonth result = yearmonth.plusMonths(5);
// print results
System.out.println("Modified YearMonth: "
+ result);
}
}
输出:
Modified YearMonth: 2020-10
方案二:
// Java program to demonstrate
// YearMonth.plusMonths() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create YearMonth object
YearMonth yearmonth
= YearMonth.parse("2019-05");
// apply plusMonths() method
// of YearMonth class
// Adding 10 months into it will turn
// it to 3rd month of next year
YearMonth result
= yearmonth.plusMonths(10);
// print results
System.out.println("Modified YearMonth: "
+ result);
}
}
输出:
Modified YearMonth: 2020-03
参考资料: https: Java/time/YearMonth.html#plusMonths(long)