java.time.Period.withYears() Method Example



Description

The java.time.Period.withYears(int years) method returns a copy of this Period with the specified years.

Declaration

Following is the declaration for java.time.Period.withYears(int years) method.

public Period withYears(int years)

Parameters

years − the years to represent, may be negative.

Return Value

a Period based on this period with the requested years, not null.

Example

The following example shows the usage of java.time.Period.withYears(int years) method.

package com.tutorialspoint;

import java.time.Period;

public class PeriodDemo {
   public static void main(String[] args) {

      Period period = Period.ofYears(2);
      System.out.println(period.toString());  
      period = period.withYears(5);
      System.out.println(period.toString());  
   }
}

Let us compile and run the above program, this will produce the following result −

P2Y
P5Y
Advertisements