📜  Java中的句点减法()方法与示例

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

Java中的句点减法()方法与示例

Java中 Period 类的 minus() 方法用于从指定的周期中减去给定的周期量。此功能在 YEAR、MONTH 和 DAY 上分别运行。

注意:不执行标准化。 12个月和1年是不同的。

句法:

public Period minus(TemporalAmount amountToSubtract)

参数:此方法接受单个参数amountToSubtract ,这是要从该期间减去的金额。它不能为空。

返回值:此方法返回一个基于给定周期减去请求周期的周期,并且不能为空。

例外:

  • DateTimeException :如果指定数量具有非 ISO 年表或包含无效单位,则返回此异常。
  • ArithmeticException :如果发生数字溢出,则会捕获此异常。

下面的程序说明了上述方法:

程序 1

// Java code to show the function minus()
// to subtract the two given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodDemo {
  
    // Function to subtract two given periods
    static void subtractPeriod(Period p1, Period p2)
    {
  
        System.out.println(p1.minus(p2));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        // Defining first period
        int year = 4;
        int months = 11;
        int days = 10;
        Period p1 = Period.of(year, months, days);
  
        // Defining second period
        int year1 = 2;
        int months1 = 7;
        int days1 = 8;
        Period p2 = Period.of(year1, months1, days1);
  
        subtractPeriod(p1, p2);
    }
}
输出:
P2Y4M2D

方案二

// Java code to show the function minus()
// to subtract the two given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
  
public class PeriodDemo {
  
    // Function to subtract two given periods
    static void subtractPeriod(Period p1, Period p2)
    {
  
        System.out.println(p1.minus(p2));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Defining second period
        int year1 = 2;
        int months1 = 7;
        int days1 = 8;
        Period p1 = Period.of(year1, months1, days1);
  
        // Defining first period
        int year = 4;
        int months = 11;
        int days = 10;
        Period p2 = Period.of(year, months, days);
  
        subtractPeriod(p1, p2);
    }
}
输出:
P-2Y-4M-2D

参考:https: Java/time/Period.html#minus-java.time.temporal.TemporalAmount-