Java ChronoPeriod addTo()方法及示例

来源:这里教程网 时间:2026-02-17 20:41:13 作者:

Java ChronoPeriod addTo()方法及示例

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

参考资料 : https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoPeriod.html#addTo-java.time.temporal.Temporal-

相关推荐