Java ZonedDateTime withHour()方法及示例
withHour() 方法是 ZonedDateTime 类的一个方法,用来改变这个ZonedDateTime中的小时数,并在操作后返回ZonedDateTime的副本。这个方法在本地时间线上操作,改变本地日期时间的时间,在这个操作后,本地日期时间被转换回ZonedDateTime,使用区域ID来获得偏移。当转换回ZonedDateTime时,如果本地日期时间处于重叠状态,那么可能的话将保留偏移量,否则,将使用较早的偏移量。这个实例是不可改变的,不受这个方法调用的影响。
语法
public ZonedDateTime withHour(int hour)
参数: 该方法接受一个参数hour,代表要在结果中设置的小时,从0到23。
返回值: 该方法返回一个基于该日期时间的ZonedDateTime,并带有要求的小时。
异常: 如果小时值无效,该方法会抛出DateTimeException。
下面的程序说明了withHour()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.withHour() 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 hour: "
+ zoneddatetime);
// alter hour to 20
ZonedDateTime returnvalue
= zoneddatetime.withHour(20);
// print result
System.out.println("ZonedDateTime after "
+ "alter hour: "
+ returnvalue);
}
}
输出。
ZonedDateTime before alter hour: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after alter hour: 2018-12-06T20:21:12.123+05:30[Asia/Calcutta]
程序2 :
// Java program to demonstrate
// ZonedDateTime.withHour() 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 hour: "
+ zoneddatetime);
// alter hour to 0
ZonedDateTime returnvalue
= zoneddatetime.withHour(0);
// print result
System.out.println("ZonedDateTime after "
+ "alter hour: "
+ returnvalue);
}
}
输出。
ZonedDateTime before alter hour: 2018-10-25T23:12:31.123+02:00[Europe/Paris]
ZonedDateTime after alter hour: 2018-10-25T00:12:31.123+02:00[Europe/Paris]
参考资料: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withHour(int)