Java中Period類的minusMonths()方法用於從給定期間減去指定的月份。此方法僅在MONTHS上有效,而不會影響其他兩個YEAR,DAYS。
用法:
public Period minusMonths(long monthsToSubtract)
參數:此方法接受單個參數monthsToSubtract,這是要從期間中減去的月份數。
返回值:此方法將根據輸入中提供的期間減去指定的月數返回一個期間。不能為空。
異常:它引發ArithmeticException。如果發生數字溢出,則會捕獲此異常。
以下示例程序旨在說明上述方法:
程序1:
// Java code to show the function minusMonths()
// to subtract the number of months from given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodClass {
// Function to subtract two given periods
static void subtractMonths(Period p1, int monthstoSubtract)
{
System.out.println(p1.minusMonths(monthstoSubtract));
}
// 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 monthstoSubtract = 8;
subtractMonths(p1, monthstoSubtract);
}
}
輸出:
P4Y3M10D
程序2:
// Java code to show the function minusMonths()
// to subtract the number of months from given periods
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodClass {
// Function to subtract two given periods
static void subtractMonths(Period p1, int monthstoSubtract)
{
System.out.println(p1.minusMonths(monthstoSubtract));
}
// 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 monthstoSubtract = -8;
subtractMonths(p1, monthstoSubtract);
}
}
輸出:
P-4Y-3M-10D
參考: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#minusMonths-long-
相關用法
- Java ZonedDateTime minusMonths()用法及代碼示例
- Java LocalDate minusMonths()用法及代碼示例
- Java OffsetDateTime minusMonths()用法及代碼示例
- Java Period from()用法及代碼示例
- Java Period plus()用法及代碼示例
- Java Period between()用法及代碼示例
- Java Period of()用法及代碼示例
- Java Period get()用法及代碼示例
- Java Period ofMonths()用法及代碼示例
- Java Period ofWeeks()用法及代碼示例
- Java Period plusYears()用法及代碼示例
- Java Period getUnits()用法及代碼示例
- Java Period parse()用法及代碼示例
- Java Period minusDays()用法及代碼示例
- Java Period hashCode()用法及代碼示例
注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 Period minusMonths() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。