Period plusYears() method in Java with Examples
Last Updated :
27 Nov, 2018
The plusYears() method of Period class in Java is used to add the given years to this period. This functions operates only on YEARS and does not affect MONTH and DAYS.
Syntax:
public Period plusYears(long yearsToAdd)
Parameters: This method accepts a single parameter yearsToAdd which is the number of years to be added to the period.
Return Value: This method returns a Period based on provided period in the input adding the specified number of years. It must not be null.
Exceptions: It throws an ArithmeticException. This exception is caught if numeric overflow occurs.
Below programs illustrate the above method:
Program 1:
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodClass {
static void addYears(Period p1, int yearstoAdd)
{
System.out.println(p1.plusYears(yearstoAdd));
}
public static void main(String[] args)
{
int year = 4 ;
int months = 11 ;
int days = 10 ;
Period p1 = Period.of(year, months, days);
int yearstoAdd = 8 ;
addYears(p1, yearstoAdd);
}
}
|
Program 2: Period can be negative.
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodClass {
static void addYears(Period p1, int yearstoAdd)
{
System.out.println(p1.plusYears(yearstoAdd));
}
public static void main(String[] args)
{
int year = - 4 ;
int months = - 11 ;
int days = 0 ;
Period p1 = Period.of(year, months, days);
int yearstoAdd = 8 ;
addYears(p1, yearstoAdd);
}
}
|
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#plusYears-long-
Share your thoughts in the comments
Please Login to comment...