当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Period minus()用法及代码示例


Java中Period类的minus()方法用于从指定的周期中减去给定的周期数。此函数分别在YEAR,MONTH和DAY运行。

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

用法:


public Period minus(TemporalAmount amountToSubtract)

参数:此方法接受单个参数amountToSubtract,这是从此时间段中减去的数量。不能为空。

返回值:此方法基于给定的时间段返回一个时间段,并减去所请求的时间段,并且该值不能为null。

异常:

  • 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

程序2

// 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://docs.oracle.com/javase/8/docs/api/java/time/Period.html#minus-java.time.temporal.TemporalAmount-



相关用法


注:本文由纯净天空筛选整理自barykrg大神的英文原创作品 Period minus() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。