📌  相关文章
📜  Java中的 Duration addTo(Temporal) 方法及示例

📅  最后修改于: 2022-05-13 01:55:11.069000             🧑  作者: Mango

Java中的 Duration addTo(Temporal) 方法及示例

使用Java.time 包Duration 类addTo(Temporal)方法将此持续时间添加到指定的时间对象,作为参数传递。

句法:

public Temporal addTo?(Temporal temporalObject)

参数:此方法接受参数temporalObject ,该参数是在此持续时间内要调整的数量。它不应该为空。

返回值:该方法返回一个同类型的对象,并调整了temporalObject。

异常:此方法抛出:

  • DateTimeException : 如果无法添加。
  • ArithmeticException : 如果发生数值溢出。

下面的示例说明了 Duration.addTo() 方法:

示例 1:

// Java code to illustrate addTo() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration 1 using parse() method
        Duration duration1
            = Duration.parse("P2DT3H4M");
  
        // Get the time to be adjusted
        LocalDateTime currentTime
            = LocalDateTime.now();
  
        System.out.println("Original time: "
                           + currentTime);
  
        // Adjust the time
        // using addTo() method
        System.out.println(
            duration1
                .addTo(currentTime));
    }
}
输出:
Original time: 2018-11-26T07:01:13.535
2018-11-28T10:05:13.535

示例 2:

// Java code to illustrate addTo() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Duration
        Duration duration2
            = Duration.ofDays(-5);
  
        // Get the time to be adjusted
        LocalDateTime currentTime
            = LocalDateTime.now();
  
        System.out.println("Original time: "
                           + currentTime);
  
        // Adjust the time
        // using addTo() method
        System.out.println(
            duration2
                .addTo(currentTime));
    }
}
输出:
Original time: 2018-11-26T07:01:16.615
2018-11-21T07:01:16.615

参考: Oracle 文档