HomeLanguagesJavaPeriod minusDays() method in Java with Examples

Period minusDays() method in Java with Examples

The minusDays() method of Period class in Java is used to subtract the days from this Period. This functions operates only on DAYS and does not affect YEAR and MONTH.

Syntax:

public Period minusDays(long daysToSubtract)

Parameters: This method accepts a single parameter daysToSubtract which is the number of days to be subtracted from the period.

Return Value: This method returns a Period based on provided period in the input
subtracting the specified number of days. 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:




// Java code to show the function minusDays()
// to subtract the number of days from given periods
  
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to subtract two given periods
    static void subtractDays(Period p1, int daystoSubtract)
    {
  
        System.out.println(p1.minusDays(daystoSubtract));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // Defining first period
        int year = 4;
        int months = 11;
        int days = 10;
        Period p1 = Period.of(year, months, days);
  
        int daystoSubtract = 8;
  
        subtractDays(p1, daystoSubtract);
    }
}


Output:

P4Y11M2D

Program 2:




// Java code to show the function minusDays()
// to subtract the number of days from given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodClass {
  
    // Function to subtract two given periods
    static void subtractDays(Period p1, int daystoSubtract)
    {
  
        System.out.println(p1.minusDays(daystoSubtract));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining first period
        int year = -4;
        int months = -11;
        int days = 0;
        Period p1 = Period.of(year, months, days);
  
        int daystoSubtract = 8;
  
        subtractDays(p1, daystoSubtract);
    }
}


Output:

P-4Y-11M-8D

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#minusDays-long-

RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32715 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7093 POSTS0 COMMENTS
Nicole Veronica
12231 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12315 POSTS0 COMMENTS
Shaida Kate Naidoo
7209 POSTS0 COMMENTS
Ted Musemwa
7474 POSTS0 COMMENTS
Thapelo Manthata
7195 POSTS0 COMMENTS
Umr Jansen
7173 POSTS0 COMMENTS