Java Period minus()方法及实例
Java中Period类的minus()方法是用来从指定的周期中减去给定的周期量的。这个函数分别对年、月和日进行操作。
注意: 不进行归一化处理。12个月和1年是不同的。
语法
public Period minus (TemporalAmount amountToSubtract)
参数: 该方法接受一个单参数 amountToSubtract ,它是要从这个时期减去的 金额 。它不能是空的。
返回值: 该方法返回一个基于给定周期并减去所要求的周期的Period,该值不能为空。
异常情况
DateTimeException : 如果指定的金额有一个非ISO的时间顺序或者包含一个无效的单位,则返回这个异常。ArithmeticException : 如果发生数字溢出,将捕获此异常。下面的程序说明了上述方法。
程序1 :
// Java code to show the function minus()// to subtract the two given periodsimport 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 periodsimport 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-
