使用java.time.chrono包中ChronoPeriod接口的addTo(Temporal)方法将此ChronoPeriod添加到指定的临时对象中,作为参数传递。
用法:
Temporal addTo(Temporal temporalObject)
参数:此方法接受参数TemporalObject,该参数是在此ChronoPeriod中要调整的数量。它不能为空。
返回值:此方法返回一个相同类型的对象,将其TemporalObject调整为该对象。
异常:该方法抛出:
DateTimeException:如果无法添加。
ArithmeticException:如果发生数字溢出。
以下示例说明了ChronoPeriod.addTo()方法:
程序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));
}
}
输出:
2024-05-27T14:23:35.242
程序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));
}
}
输出:
2022-01-25T14:23:50.411