📜  Java中的 YearMonth minusMonths() 方法及示例

📅  最后修改于: 2022-05-13 01:54:39.354000             🧑  作者: Mango

Java中的 YearMonth minusMonths() 方法及示例

Java中YearMonth类的minusMonths()方法用于返回此 YearMonth 的副本,其中减去了指定的月数。
句法:

public YearMonth minusMonths(
        long monthsToSubtract)

参数:此方法接受monthToSubtract作为参数,表示要减去的月份。它可能是负面的。
返回值:它返回基于此年月减去月份的YearMonth
异常:如果结果超出支持的范围,此方法将引发DateTimeException
下面的程序说明了Java中 YearMonth 的 minusMonths() 方法:
方案一:

Java
// Java program to demonstrate
// YearMonth.minusMonths() method
 
import java.time.*;
import java.time.temporal.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // create YearMonth object
        YearMonth yearmonth
            = YearMonth.parse("2020-05");
        // It is May 2020
 
        // apply minusMonths() method
        // of YearMonth class
        YearMonth result
            = yearmonth.minusMonths(2);
        // It subtracts 2 months from May 2020
        // So it will be March 2020
 
        // print year and month both
        System.out.println("Modified YearMonth: "
                           + result);
    }
}


Java
// Java program to demonstrate
// YearMonth.minusMonths() method
 
import java.time.*;
import java.time.temporal.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // create YearMonth object
        YearMonth yearmonth
            = YearMonth.parse("2019-10");
 
        // apply minusMonths() method
        // of YearMonth class
        YearMonth result
            = yearmonth.minusMonths(10);
        // Subtracting 10 months will turn it into
        // December of 2018 (previous year)
 
        // print year and month both
        System.out.println(
            "Modified YearMonth: "
            + result);
    }
}


输出:
Modified YearMonth: 2020-03

方案二:

Java

// Java program to demonstrate
// YearMonth.minusMonths() method
 
import java.time.*;
import java.time.temporal.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // create YearMonth object
        YearMonth yearmonth
            = YearMonth.parse("2019-10");
 
        // apply minusMonths() method
        // of YearMonth class
        YearMonth result
            = yearmonth.minusMonths(10);
        // Subtracting 10 months will turn it into
        // December of 2018 (previous year)
 
        // print year and month both
        System.out.println(
            "Modified YearMonth: "
            + result);
    }
}
输出:
Modified YearMonth: 2018-12

参考资料: https: Java/time/YearMonth.html#minusMonths(long)