Java Period minusYears()方法及示例
Java中Period类的 minusYears() 方法用于从给定的周期中减去指定的年份。这个函数只对年进行操作,不影响其他两个月和日。
语法
public Period minusYears(long yearsToSubtract)
参数: 该方法接受一个参数 yearsToSubtract,它是要从周期中减去的年份数。
返回值 :该方法返回一个基于输入中提供的周期减去指定年数的周期。它不能是空的。
异常: 它抛出一个 ArithmeticException。 如果发生数字溢出,这个异常将被捕获。
下面的程序说明了上述方法。
程序1 :
// Java code to show the function minusYears()// to subtract the number of years from given periodimport java.time.Period;import java.time.temporal.ChronoUnit; public class PeriodClass { // Function to subtract two given periods static void subtractYears(Period p1, int yearstoSubtract) { System.out.println(p1.minusYears(yearstoSubtract)); } // 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); int yearstoSubtract = 8; subtractYears(p1, yearstoSubtract); }}
输出:
P-4Y11M10D
程序2 :
// Java code to show the function minusYears()// to subtract the number of years from given periodimport java.time.Period;import java.time.temporal.ChronoUnit; public class PeriodClass { // Function to subtract two given periods static void subtractYears(Period p1, int yearstoSubtract) { System.out.println(p1.minusYears(yearstoSubtract)); } // 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); int yearstoSubtract = -8; subtractYears(p1, yearstoSubtract); }}输出:
P12Y11M10D
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#minusYears-long-
