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()方法:
示例1:
// 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
示例2:
// 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://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#withDayOfMonth(int)
相关用法
- Java LocalDate withDayOfMonth()用法及代码示例
- Java OffsetDateTime withDayOfMonth()用法及代码示例
- Java MonthDay withDayOfMonth()用法及代码示例
- Java ZonedDateTime withDayOfMonth()用法及代码示例
- Java LocalDateTime now()用法及代码示例
- Java LocalDateTime plus()用法及代码示例
- Java LocalDateTime from()用法及代码示例
- Java LocalDateTime with()用法及代码示例
- Java LocalDateTime until()用法及代码示例
- Java LocalDateTime withHour()用法及代码示例
- Java LocalDateTime plusSeconds()用法及代码示例
- Java LocalDateTime plusNanos()用法及代码示例
- Java LocalDateTime getDayOfMonth()用法及代码示例
- Java LocalDateTime plusWeeks()用法及代码示例
- Java LocalDateTime parse()用法及代码示例
注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 LocalDateTime withDayOfMonth() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。