Java MonthDay withDayOfMonth()方法及示例

Java MonthDay withDayOfMonth()方法及示例

MonthDay 类的 withDayOfMonth(int dayOfMonth) 方法用于改变MonthDay对象的月日,使用dayOfMonth作为参数传递,之后该方法返回改变后的MonthDay副本。

语法

public MonthDay withDayOfMonth(int dayOfMonth)

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

返回值: 该方法返回一个基于该月日的MonthDay,该月日为要求的日期。

异常: 如果月日值无效,或者月日对该月来说是无效的,该方法会抛出 DateTimeException

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

程序1 :

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

程序2

// 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://docs.oracle.com/javase/10/docs/api/java/time/MonthDay.html#withDayOfMonth(int)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程