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

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

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

用于更改 MonthDay 对象的月份日期的MonthDay类的withDayOfMonth(int dayOfMonth)方法,使用作为参数传递的 dayOfMonth 并在该方法之后返回更改后的 MonthDay 的副本。如果是月份的日期,则会引发异常变更操作后指定月份的值无效。

句法:

public MonthDay withDayOfMonth(int dayOfMonth)

参数:此方法接受dayOfMonth作为参数,这是要在返回月日中设置的月日,从 1 到 31。

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

异常:如果月份的日期值无效,或者月份的日期对月份无效,则此方法将引发DateTimeException

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

// Java program to demonstrate
// MonthDay.withDayOfMonth() 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 withDayOfMonth method
        // of MonthDay class
        MonthDay updatedlocal
            = monthday.withDayOfMonth(21);
  
        // print instance
        System.out.println("MonthDay after"
                           + " applying method: "
                           + updatedlocal);
    }
}
输出:
MonthDay before applying method: --08-28
MonthDay after applying method: --08-21

方案二:

// Java program to demonstrate
// MonthDay.withDayOfMonth() 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 withDayOfMonth method
        // of MonthDay class
        MonthDay updatedlocal
            = monthday.withDayOfMonth(12);
  
        // print instance
        System.out.println("MonthDay after"
                           + " applying method: "
                           + updatedlocal);
    }
}
输出:
MonthDay before applying method: --10-31
MonthDay after applying method: --10-12

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