Sunday, November 23, 2025
HomeLanguagesJavaChronoPeriod subtractFrom() method in Java with Examples

ChronoPeriod subtractFrom() method in Java with Examples

The subtractFrom(Temporal) method of ChronoPeriod Interface in java.time.chrono package is used subtract this ChronoPeriod to the specified temporal object, passed as the parameter.

Syntax:

Temporal subtractFrom(Temporal temporalObject)

Parameters: This method accepts a parameter temporalObject which is the amount to be adjusted in this ChronoPeriod. It should not be null.

Return Value: This method returns an object of the same type with the temporalObject adjusted to it.

Exception: This method throws:

  • DateTimeException: if unable to subtract.
  • ArithmeticException: if numeric overflow occurs.

Below examples illustrate the ChronoPeriod.subtractFrom() method:

Program 1:




// Java code to show the function subtractFrom()
// to subtract the two given periods
  
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.ChronoUnit;
  
public class ChronoPeriodDemo {
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining period
        int year = 4;
        int months = 11;
        int days = 10;
        ChronoPeriod p1 = Period.of(year, months, days);
  
        // Get the time to be adjusted
        LocalDateTime currentTime
            = LocalDateTime.now();
  
        // Adjust the time
        // using subtractFrom() method
        System.out.println(
            p1.subtractFrom(currentTime));
    }
}


Output:

2014-07-07T14:22:21.929

Program 2:




// Java code to show the function subtractFrom()
// to subtract the two given periods
  
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.ChronoUnit;
  
public class ChronoPeriodDemo {
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining period
        int year1 = 2;
        int months1 = 7;
        int days1 = 8;
        ChronoPeriod p1 = Period.of(year1, months1, days1);
  
        // Get the time to be adjusted
        LocalDateTime currentTime
            = LocalDateTime.now();
  
        // Adjust the time
        // using subtractFrom() method
        System.out.println(
            p1.subtractFrom(currentTime));
    }
}


Output:

2016-11-09T14:22:26.600

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoPeriod.html#subtractFrom-java.time.temporal.Temporal-

RELATED ARTICLES

Most Popular

Dominic
32409 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6908 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6865 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS