Java中的 OffsetDateTime withMonth() 方法及示例
Java中 OffsetDateTime 类的withMonth()方法返回此 OffsetDateTime 的副本,其中年份的月份按参数中指定的方式更改。
句法:
public OffsetDateTime withMonth(int month)
参数:此方法接受单个参数月份,该参数指定要在结果中设置的月份,范围从 1 到 12。
返回值:它基于此日期返回一个 OffsetDateTime,其中包含请求的月份且不为空。
异常:当月份值无效时,程序会抛出DateTimeException 。
下面的程序说明了withMonth()方法:
方案一:
// Java program to demonstrate the withMonth() method
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
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 month-of-year
System.out.println("Date1 after altering month-of-year: "
+ date1.withMonth(10));
}
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering month-of-year: 2018-10-12T13:30:30+05:00
方案二:
// Java program to demonstrate the withMonth() 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 minute of day
System.out.println("Date1 after altering month-of-year: "
+ date1.withMonth(27));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 27
参考:https: Java/time/OffsetDateTime.html#withMonth(int)