📌  相关文章
📜  Java中的 MonthDay withMonth() 方法及示例

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

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

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

句法:

public MonthDay withMonth(int month)

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

返回值:此方法根据请求月份的本月日返回一个 MonthDay。

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

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

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

方案二:

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

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