Period withYears() method in Java


An immutable copy of a Period with the number of years as required is done using the method withYears() in the Period class in Java. This method requires a single parameter i.e. the number of years in the Period and it returns the Period with the number of years as required.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      String period = "P5Y7M15D";
      Period p1 = Period.parse(period);
      System.out.println("The Period is: " + p1);
      Period p2 = p1.withYears(3);
      System.out.println("The Period with years altered to 3 is: " + p2);
   }
}

Output

The Period is: P5Y7M15D
The Period with years altered to 3 is: P3Y7M15D

Now let us understand the above program.

First the Period is displayed. Then the Period with the number of years altered to 3 is displayed using the method withYears(). A code snippet that demonstrates this is as follows:

String period = "P5Y7M15D";
Period p1 = Period.parse(period);
System.out.println("The Period is: " + p1);
Period p2 = p1.withYears(3);
System.out.println("The Period with years altered to 3 is: " + p2);

Updated on: 30-Jul-2019

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements