Java Period minusMonths()方法及示例

来源:这里教程网 时间:2026-02-17 21:05:42 作者:

Java Period minusMonths()方法及示例

Java中Period类的minusMonths()方法是用来从给定的周期中减去指定的月份。该方法只对月份进行操作,不影响其他两个年份和日期。

语法

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-

相关推荐