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

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

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

Java中LocalDateTime 类withDayOfMonth()方法用于获取此 LocalDateTime 的副本,其中 dayOfMonth 更改为 dayOfMonth 作为参数传递给该方法。此 LocalDateTime 的其余值保持不变。

句法:

public LocalDateTime withDayOfMonth(int dayOfMonth)

参数:此方法接受一个强制参数dayOfMonth ,它指定要在结果 LocalDateTime 实例中设置的 dayOfMonth。此 dayOfMonth 的值范围为 1 到 31。

返回:该函数返回一个LocalDateTime 实例,其中 dayOfMonth 更改为 dayOfMonth 作为参数传递给此方法。此 LocalDateTime 的其余值保持不变。

异常:如果 dayOfMonth 值无效,该函数将引发DateTimeException

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

方案一:

// Program to illustrate the withDayOfMonth() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Get the LocalDateTime instance
        LocalDateTime dt = LocalDateTime.now();
  
        // Get the String representation of this LocalDateTime
        System.out.println("Original LocalDateTime: "
                           + dt.toString());
  
        // Get a new LocalDateTime with dayOfMonth 25
        System.out.println("New LocalDateTime: "
                           + dt.withDayOfMonth(25));
    }
}
输出:
Original LocalDateTime: 2018-11-30T10:38:27.429
New LocalDateTime: 2018-11-25T10:38:27.429

方案二:

// Program to illustrate the withDayOfMonth() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Get the LocalDateTime instance
        LocalDateTime dt
            = LocalDateTime
                  .parse("2015-04-06T10:15:30");
  
        // Get the String representation of this LocalDateTime
        System.out.println("Original LocalDateTime: "
                           + dt.toString());
  
        // Get a new LocalDateTime with dayOfMonth 1
        System.out.println("New LocalDateTime: "
                           + dt.withDayOfMonth(1));
    }
}
输出:
Original LocalDateTime: 2015-04-06T10:15:30
New LocalDateTime: 2015-04-01T10:15:30

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