Java中的 ZonedDateTime withZoneSameInstant() 方法及示例
ZonedDateTime类的withZoneSameInstant()方法用于通过更改时区而不是瞬间返回此 ZonedDateTime 对象的副本。该方法基于保留同一时刻,因此本地时间线中的间隙和重叠对结果没有影响。
句法:
public ZonedDateTime withZoneSameInstant(ZoneId zone)
参数:此方法接受一个参数zone来更改时区。它不应该为空。
返回值:此方法基于此日期时间与请求的区域返回ZonedDateTime 。
抛出异常:如果结果超出支持的日期范围,则DateTimeException 。
示例 1:
Java
// Java program to demonstrate
// ZonedDateTime.withZoneSameInstant() method
// Importing required classes
import java.time.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a ZonedDateTime object
ZonedDateTime zonedDT = ZonedDateTime.parse(
"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
// Printing ZonedDateTime of Calcutta on console
System.out.println("ZonedDateTime of Calcutta: "
+ zonedDT);
// Applying withZoneSameInstant()
ZonedDateTime zonedDT2
= zonedDT.withZoneSameInstant(
ZoneId.of("Pacific/Fiji"));
// Now printing ZonedDateTime of Fuji
// after withZoneSameInstant()
System.out.println("ZonedDateTime of Fuji: "
+ zonedDT2);
}
}
Java
// Java program to Demonstrate
// ZonedDateTime.withZoneSameInstant() method
// Importing required classes
import java.time.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a ZonedDateTime object and
// passing date and time of Europe/Paris
ZonedDateTime zonedDT = ZonedDateTime.parse(
"2018-10-25T23:12:31.123+02:00[Europe/Paris]");
// Printing ZonedDateTime of Paris on console
// before applying withZoneSameInstant() method
System.out.println("ZonedDateTime of Paris: "
+ zonedDT);
// Now applying withZoneSameInstant() method
ZonedDateTime zonedDT2
= zonedDT.withZoneSameInstant(
ZoneId.of("Canada/Yukon"));
// Printing ZonedDateTime
// after applying withZoneSameInstant()
System.out.println("ZonedDateTime of Yukon: "
+ zonedDT2);
}
}
输出:
ZonedDateTime of Calcutta: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime of Fuji: 2018-12-07T02:51:12.123+13:00[Pacific/Fiji]
示例 2:
Java
// Java program to Demonstrate
// ZonedDateTime.withZoneSameInstant() method
// Importing required classes
import java.time.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a ZonedDateTime object and
// passing date and time of Europe/Paris
ZonedDateTime zonedDT = ZonedDateTime.parse(
"2018-10-25T23:12:31.123+02:00[Europe/Paris]");
// Printing ZonedDateTime of Paris on console
// before applying withZoneSameInstant() method
System.out.println("ZonedDateTime of Paris: "
+ zonedDT);
// Now applying withZoneSameInstant() method
ZonedDateTime zonedDT2
= zonedDT.withZoneSameInstant(
ZoneId.of("Canada/Yukon"));
// Printing ZonedDateTime
// after applying withZoneSameInstant()
System.out.println("ZonedDateTime of Yukon: "
+ zonedDT2);
}
}
输出
ZonedDateTime of Paris: 2018-10-25T23:12:31.123+02:00[Europe/Paris]
ZonedDateTime of Yukon: 2018-10-25T14:12:31.123-07:00[Canada/Yukon]