ChronoPeriod addTo() method in Java with Examples
The addTo(Temporal) method of ChronoPeriod Interface in java.time.chrono package is used add this ChronoPeriod to the specified temporal object, passed as the parameter.
Syntax:
Temporal addTo(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 add.
- ArithmeticException: if numeric overflow occurs.
Below examples illustrate the ChronoPeriod.addTo() method:
Program 1:
// Java code to show the function addTo() // to add 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 addTo() method System.out.println( p1.addTo(currentTime)); } } |
Output:
2024-05-27T14:23:35.242
Program 2:
// Java code to show the function addTo() // to add 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 addTo() method System.out.println( p1.addTo(currentTime)); } } |
Output:
2022-01-25T14:23:50.411
Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoPeriod.html#addTo-java.time.temporal.Temporal-
Contact Us