Thursday, April 2, 2026
HomeLanguagesJavaPeriod withYears() method in Java with Examples

Period withYears() method in Java with Examples

The withYears() method of Period Class is used to obtain a period with specified number of years. This number of years is passed as the parameter as integer value.

Syntax:

public Period withYears(int numberOfYears)

Parameters: This method accepts a parameter numberOfYears which is the number of years to be changed in this Period.

Returns: This function returns a Period with the number of years passed as the parameter.

Below is the implementation of Period.withYears() method:

Example 1:




// Java code to demonstrate withYears() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be withYearsd
        String period = "P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the number of years
        int numberOfYears = 5;
  
        // Change the numberOfYears of this Period
        // using withYears() method
        System.out.println("New Period: "
                           + p.withYears(numberOfYears));
    }
}


Output:

Period: P1Y2M21D
New Period: P5Y2M21D

Example 2:




// Java code to demonstrate withYears() method
  
import java.time.Period;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the String to be withYearsd
        String period = "-P1Y2M21D";
  
        // Parse the String into Period
        Period p = Period.parse(period);
  
        System.out.println("Period: " + p);
  
        // Get the number of years
        int numberOfYears = -5;
  
        // Change the numberOfYears of this Period
        // using withYears() method
        System.out.println("New Period: "
                           + p.withYears(numberOfYears));
    }
}


Output:

Period: P-1Y-2M-21D
New Period: P-5Y-2M-21D

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#withYears-int-

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32509 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6885 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12100 POSTS0 COMMENTS
Shaida Kate Naidoo
7013 POSTS0 COMMENTS
Ted Musemwa
7257 POSTS0 COMMENTS
Thapelo Manthata
6968 POSTS0 COMMENTS
Umr Jansen
6958 POSTS0 COMMENTS