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

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

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

YearMonth类的withMonth(int month)方法,用于使用作为参数传递的月份来更改 YearMonth 对象的月份,并在该方法之后返回更改后的 YearMonth 的副本。如果月份的日期对指定月份,日期将调整为该月的最后一个有效日期。此实例是不可变的,不受此方法调用的影响。

句法:

public YearMonth withMonth(int month)

参数:此方法接受月份作为参数,该参数是要在返回的年月中设置的年月,从 1(一月)到 12(十二月)。

返回值:此方法根据请求的月份返回基于此年月的 YearMonth。

异常:如果月份值无效,此方法将引发DateTimeException

下面的程序说明了 withMonth() 方法:
方案一:

// Java program to demonstrate
// YearMonth.withMonth() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a YearMonth object
        YearMonth yr
            = YearMonth.of(2019, 12);
  
        // print instance
        System.out.println("YearMonth before"
                           + " applying method: "
                           + yr);
  
        // apply withMonth method of YearMonth class
        YearMonth updatedlocal = yr.withMonth(1);
  
        // print instance
        System.out.println("YearMonth after"
                           + " applying method: "
                           + updatedlocal);
    }
}
输出:
YearMonth before applying method: 2019-12
YearMonth after applying method: 2019-01

方案二:

// Java program to demonstrate
// YearMonth.withMonth() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a YearMonth object
        YearMonth yr
            = YearMonth.of(2022, 7);
  
        // print instance
        System.out.println("YearMonth before"
                           + " applying method: "
                           + yr);
  
        // apply withMonth method of YearMonth class
        YearMonth updatedlocal = yr.withMonth(12);
  
        // print instance
        System.out.println("YearMonth after"
                           + " applying method: "
                           + updatedlocal);
    }
}
输出:
YearMonth before applying method: 2022-07
YearMonth after applying method: 2022-12

参考资料: https: Java/time/YearMonth.html#withMonth(int)