📌  相关文章
📜  Java中的 ChronoPeriod SubtractFrom() 方法及示例

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

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

方案二

// 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-