📜  Java中的 LocalDate withDayOfMonth() 方法及示例

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

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

Java中LocalDate 类withDayOfMonth()方法返回此 LocalDate 的副本,其中日期已更改。

句法:

public LocalDate withDayOfMonth(int dayOfMonth)

参数:此方法接受一个强制参数dayOfMonth ,在结果中设置日期,从 1 到 28-31。

返回:该函数返回一个基于此日期的 LocalDate 和请求的日期,而不是 null。

异常:当月份的日期值无效时,该函数会引发DateTimeException

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

方案一:

// Program to illustrate the withDayOfMonth() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
  
        // Parses the date
        LocalDate dt1 = LocalDate.parse("2018-12-07");
        LocalDate result = dt1.withDayOfMonth(01);
  
        // Prints the date with year
        System.out.println("The date with day of the month is: " + result);
    }
}
输出:
The date with day of the month is: 2018-12-01

方案二:

// Program to illustrate the withDayOfMonth() method
// Exceptions
import java.util.*;
import java.time.*;
import java.time.temporal.ChronoField;
  
public class GfG {
    public static void main(String[] args)
    {
  
        try {
            // Parses the date
            LocalDate dt1 = LocalDate.parse("2018-12-07");
            LocalDate result = dt1.withDayOfMonth(35);
  
            // Prints the date with year
            System.out.println("The date with day of the month is: " + result);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 35

参考: https: Java/time/LocalDate.html#withDayOfMonth(int)