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

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

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

Java中 OffsetDateTime 类的withDayOfMonth()方法返回此 OffsetDateTime 的副本,其中日期按参数中指定的方式更改。

句法:

public OffsetDateTime withDayOfMonth(int dayOfMonth)

参数:此方法接受单个参数dayOfMonth ,该参数指定要在结果中设置的日期,范围从 1 到 28-31。

返回值:它根据请求的日期返回一个 OffsetDateTime,并且不为空。

异常:当月份的日期值无效或该特定年份的月份的月份日期无效时,程序会抛出DateTimeException

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

方案一:

// Java program to demonstrate the withDayOfMonth() method
  
import java.time.OffsetDateTime;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Parses the date1
        OffsetDateTime date1
            = OffsetDateTime
                  .parse(
                      "2018-12-12T13:30:30+05:00");
  
        // Prints dates
        System.out.println("Date1: " + date1);
  
        // Changes the day of month
        System.out.println("Date1 after altering day-of-month: "
                           + date1.withDayOfMonth(20));
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering day-of-month: 2018-12-20T13:30:30+05:00

方案二

// Java program to demonstrate the withDayOfMonth() method
  
import java.time.OffsetDateTime;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
            // Parses the date1
            OffsetDateTime date1
                = OffsetDateTime
                      .parse(
                          "2018-12-12T13:30:30+05:00");
  
            // Prints dates
            System.out.println("Date1: " + date1);
  
            // Changes the day of month
            System.out.println("Date1 after altering day-of-month: "
                               + date1.withDayOfMonth(32));
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException:
           Invalid value for DayOfMonth (valid values 1 - 28/31): 32

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