当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java YearMonth minusYears()用法及代码示例


Java中YearMonth类的minusYears()方法用于返回该YearMonth的副本,其中减去指定的年数。

用法:

public YearMonth minusYears(long yearsToSubtract)

参数:此方法接受yearsToSubtract作为参数,代表要减去的年份。可能是负面的。



返回值:它基于此year-month返回减去年份的YearMonth。

异常:如果结果超出支持的范围,则此方法将引发DateTimeException。

以下示例程序旨在说明Java中YearMonth的minusYears()方法:

程序1:

// 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

程序2:

// 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://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#minusYears(long)




相关用法


注:本文由纯净天空筛选整理自pp_pankaj大神的英文原创作品 YearMonth minusYears() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。