Java中OffsetDateTime类的withDayOfMonth()方法返回此OffsetDateTime的副本,其中day-of-month如参数中所述进行了更改。
用法:
public OffsetDateTime withDayOfMonth(int dayOfMonth)
参数:此方法接受单个参数dayOfMonth,该参数指定要在结果中设置的day-of-month,范围为1到28-31。
返回值:它基于带有请求的日期的该日期返回OffsetDateTime,而不是null。
异常:当day-of-month值无效或该特定年份的月份的day-of-month无效时,程序将引发DateTimeException。
以下示例程序旨在说明withDayOfMonth()方法:
示例1:
// 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
程序2:
// 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://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#withDayOfMonth(int)
相关用法
- Java LocalDate withDayOfMonth()用法及代码示例
- Java MonthDay withDayOfMonth()用法及代码示例
- Java LocalDateTime withDayOfMonth()用法及代码示例
- Java ZonedDateTime withDayOfMonth()用法及代码示例
- Java OffsetDateTime with()用法及代码示例
- Java OffsetDateTime from()用法及代码示例
- Java OffsetDateTime until()用法及代码示例
- Java OffsetDateTime get()用法及代码示例
- Java OffsetDateTime getLong()用法及代码示例
- Java OffsetDateTime getDayOfMonth()用法及代码示例
- Java OffsetDateTime getHour()用法及代码示例
- Java OffsetDateTime minusMonths()用法及代码示例
- Java OffsetDateTime getMinute()用法及代码示例
- Java OffsetDateTime getMonth()用法及代码示例
- Java OffsetDateTime withNano()用法及代码示例
注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 OffsetDateTime withDayOfMonth() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。