Java ChronoPeriod subtractFrom()方法及示例

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

Java ChronoPeriod subtractFrom()方法及示例

java.time.Chrono包中ChronoPeriod接口的 subtractFrom(Temporal)方法用于将此ChronoPeriod减去指定的时间对象,作为参数传递。

语法。

Temporal subtractFrom(Temporal temporalObject)

参数。这个方法接受一个参数temporalObject,它是这个ChronoPeriod中要调整的数量。它不应该是空的。

返回值。该方法返回一个与temporalObject相同类型的调整对象。

异常情况。这个方法会抛出。

DateTimeException : 如果不能进行减法。ArithmeticException:如果发生数字溢出。

下面的例子说明了ChronoPeriod.subtractFrom()方法。

程序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));    }}

输出:

2014-07-07T14:22:21.929

程序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));    }}

输出:

2016-11-09T14:22:26.600

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

相关推荐