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


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


Java中YearMonth类的plusMonths()方法用于获取此YearMonth的副本,其中添加了指定的月数。

用法:

public YearMonth plusMonths(long monthsToAdd)

参数:此方法接受monthsToAdd作为参数,该参数表示要添加到当前YearMonth对象的月份。可能是负面的。



返回值:它基于此year-month返回添加了月份的YearMonth。

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

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

程序1:

// Java program to demonstrate 
// YearMonth.plusMonths() 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"); 
  
        // apply plusMonths() method 
        // of YearMonth class 
        // Adding 5 months into May 2020 
        // will turn it into October 2020 
        YearMonth result = yearmonth.plusMonths(5); 
  
        // print results 
        System.out.println("Modified YearMonth:"
                           + result); 
    } 
}
输出:
Modified YearMonth:2020-10

程序2:

// Java program to demonstrate 
// YearMonth.plusMonths() 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-05"); 
  
        // apply plusMonths() method 
        // of YearMonth class 
        // Adding 10 months into it will turn 
        // it to 3rd month of next year 
        YearMonth result 
            = yearmonth.plusMonths(10); 
  
        // print results 
        System.out.println("Modified YearMonth:"
                           + result); 
    } 
}
输出:
Modified YearMonth:2020-03

参考文献: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#plusMonths(long)




相关用法


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