Java中Period类的plusYears()方法用于将给定的年份添加到此期间。此功能仅在YEARS起作用,并且不影响MONTH和DAYS。
用法:
public Period plusYears(long yearsToAdd)
参数:此方法接受单个参数yearsToAdd,这是要添加到期间的年数。
返回值:此方法基于输入中提供的期间加上指定的年数来返回“期间”。不能为空。
异常:它引发ArithmeticException。如果发生数字溢出,则会捕获此异常。
以下示例程序旨在说明上述方法:
示例1:
// Java code to show the function plusYears()
// to add the number of years from given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodClass {
// Function to add years to given period
static void addYears(Period p1, int yearstoAdd)
{
System.out.println(p1.plusYears(yearstoAdd));
}
// Driver Code
public static void main(String[] args)
{
// Defining first period
int year = 4;
int months = 11;
int days = 10;
Period p1 = Period.of(year, months, days);
int yearstoAdd = 8;
addYears(p1, yearstoAdd);
}
}
输出:
P12Y11M10D
程序2:期间可以为负。
// Java code to show the function plusYears()
// to add the number of years to given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodClass {
// Function to add years to given periods
static void addYears(Period p1, int yearstoAdd)
{
System.out.println(p1.plusYears(yearstoAdd));
}
// Driver Code
public static void main(String[] args)
{
// Defining first period
int year = -4;
int months = -11;
int days = 0;
Period p1 = Period.of(year, months, days);
int yearstoAdd = 8;
addYears(p1, yearstoAdd);
}
}
输出:
P4Y-11M