當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Period minusDays()用法及代碼示例


Java中Period類的minusDays()方法用於從該Period中減去天數。此函數僅在DAYS運行,不影響YEAR和MONTH。

用法:

public Period minusDays(long daysToSubtract)

參數:此方法接受單個參數daysToSubtract,這是要從該期間中減去的天數。


返回值:此方法根據輸入中提供的時間段返回一個時間段
減去指定的天數。不能為空。

異常:它引發ArithmeticException。如果發生數字溢出,則會捕獲此異常。

以下示例程序旨在說明上述方法:

程序1

// Java code to show the function minusDays() 
// to subtract the number of days from given periods 
  
import java.time.Period; 
import java.time.temporal.ChronoUnit; 
  
public class PeriodClass { 
  
    // Function to subtract two given periods 
    static void subtractDays(Period p1, int daystoSubtract) 
    { 
  
        System.out.println(p1.minusDays(daystoSubtract)); 
    } 
  
    // 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 daystoSubtract = 8; 
  
        subtractDays(p1, daystoSubtract); 
    } 
}
輸出:
P4Y11M2D

程序2

// Java code to show the function minusDays() 
// to subtract the number of days from given periods 
import java.time.Period; 
import java.time.temporal.ChronoUnit; 
  
public class PeriodClass { 
  
    // Function to subtract two given periods 
    static void subtractDays(Period p1, int daystoSubtract) 
    { 
  
        System.out.println(p1.minusDays(daystoSubtract)); 
    } 
  
    // Driver Code 
    public static void main(String[] args) 
    { 
        // Defining first period 
        int year = -4; 
        int months = -11; 
        int days = 0; 
        Period p1 = Period.of(year, months, days); 
  
        int daystoSubtract = 8; 
  
        subtractDays(p1, daystoSubtract); 
    } 
}
輸出:
P-4Y-11M-8D

參考: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#minusDays-long-



相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 Period minusDays() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。