Java ZonedDateTime withMonth()方法及示例
withMonth() 方法是 ZonedDateTime 类的一个方法,用于改变这个ZonedDateTime中的年月日,并在此操作后返回ZonedDateTime的副本。这个方法在本地时间线上操作,改变本地日期时间的月份,在此操作后本地日期时间被转换回ZonedDateTime,使用区域ID来获得偏移。当转换回ZonedDateTime时,如果本地日期时间处于重叠状态,那么可能的话将保留偏移量,否则,将使用较早的偏移量。这个实例是不可改变的,不受这个方法调用的影响。
语法
public ZonedDateTime withMonth(int month)
参数: 该方法接受一个单一的参数月份,代表要在结果中设置的年份的月份,从1(1月)到12(12月)。
返回值: 该方法返回一个基于该日期时间的ZonedDateTime,并带有请求的月份。
异常: 如果月份值无效,该方法会抛出DateTimeException。
下面的程序说明了withMonth()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.withMonth() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zoneddatetime
= ZonedDateTime.parse(
"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
// print instance
System.out.println("ZonedDateTime before"
+ " alter month: "
+ zoneddatetime);
// alter month to 5(May)
ZonedDateTime returnvalue
= zoneddatetime.withMonth(5);
// print result
System.out.println("ZonedDateTime after "
+ "alter month: "
+ returnvalue);
}
}
输出。
ZonedDateTime before alter month: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after alter month: 2018-05-06T19:21:12.123+05:30[Asia/Calcutta]
程序2 :
// Java program to demonstrate
// ZonedDateTime.withMonth() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zoneddatetime
= ZonedDateTime.parse(
"2018-10-25T23:12:31.123+02:00[Europe/Paris]");
// print instance
System.out.println("ZonedDateTime before"
+ " alter month: "
+ zoneddatetime);
// alter month to 12(december)
ZonedDateTime returnvalue
= zoneddatetime.withMonth(12);
// print result
System.out.println("ZonedDateTime after "
+ "alter month: "
+ returnvalue);
}
}
输出。
ZonedDateTime before alter month: 2018-10-25T23:12:31.123+02:00[Europe/Paris]
ZonedDateTime after alter month: 2018-12-25T23:12:31.123+01:00[Europe/Paris]
参考资料: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withMonth(int)