Java中的 YearMonth minusYears() 示例
Java中YearMonth类的minusYears()方法用于返回减去指定年数的 YearMonth 的副本。
句法:
public YearMonth minusYears(long yearsToSubtract)
参数:此方法接受yearsToSubtract作为参数,表示要减去的年份。它可能是负面的。
返回值:它返回基于此年月减去年份的YearMonth 。
异常:如果结果超出支持的范围,此方法将引发DateTimeException 。
下面的程序说明了Java中 YearMonth 的 minusYears() 方法:
方案一:
// Java program to demonstrate
// YearMonth.minusYears() 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 minusYears() method
// of YearMonth class
YearMonth result
= yearmonth.minusYears(5);
// Subtracting 5 years will turn it
// into May 2015
// print year and month both
System.out.println(
"Modified YearMonth: "
+ result);
}
}
输出:
Modified YearMonth: 2015-05
方案二:
// Java program to demonstrate
// YearMonth.minusYears() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create YearMonth object
YearMonth yearmonth
= YearMonth.of(2019, 10);
// apply minusYears() method
// of YearMonth class
YearMonth result
= yearmonth.minusYears(10);
// Subtracting 10 years will
// turn it into October 2009
// print only year
System.out.println(
"Modified Year: "
+ result.get(ChronoField.YEAR));
}
}
输出:
Modified Year: 2009
参考资料: https: Java/time/YearMonth.html#minusYears(long)