Friday, September 26, 2025
HomeLanguagesJavaPeriod withDays() method in Java with Examples

Period withDays() method in Java with Examples

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

Syntax:

public Period withDays(int numberOfDays)

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

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

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

Example 1:




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


Output:

Period: P1Y2M21D
New Period: P1Y2M5D

Example 2:




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


Output:

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

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

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

Most Popular

Dominic
32320 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6683 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6795 POSTS0 COMMENTS
Ted Musemwa
7071 POSTS0 COMMENTS
Thapelo Manthata
6756 POSTS0 COMMENTS
Umr Jansen
6762 POSTS0 COMMENTS